Skip to content
This repository has been archived by the owner on Apr 9, 2024. It is now read-only.

Commit

Permalink
Calculate UniqueID via increment
Browse files Browse the repository at this point in the history
Instead of trying to find unique id randomly, which is costly, do it sequentially instead.
In this case, we have ~4 billion unique identifiers, and even if we exhaust them all, we will reset back to int.MinValue and start over.
It also helps getting rid of locking in the finalizer.
  • Loading branch information
Pavel Vorozheykin authored and RoadTrain committed Apr 12, 2022
1 parent 166d53b commit c9f61f4
Showing 1 changed file with 3 additions and 29 deletions.
32 changes: 3 additions & 29 deletions SevenZip/SevenZipBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public abstract class SevenZipBase : MarshalByRefObject
{
private readonly bool _reportErrors;
private readonly int _uniqueID;
private static readonly List<int> Identifiers = new List<int>();
private static int _incrementingUniqueId = int.MinValue;

/// <summary>
/// True if the instance of the class needs to be recreated in new thread context; otherwise, false.
Expand Down Expand Up @@ -103,22 +103,8 @@ internal virtual void ReleaseContext()

private static int GetUniqueID()
{
lock (Identifiers)
{
int id;

var rnd = new Random(DateTime.Now.Millisecond);

do
{
id = rnd.Next(int.MaxValue);
}
while (Identifiers.Contains(id));

Identifiers.Add(id);

return id;
}
var newUniqueId = Interlocked.Increment(ref _incrementingUniqueId);
return newUniqueId;
}

/// <summary>
Expand All @@ -132,18 +118,6 @@ protected SevenZipBase(string password = "")
_uniqueID = GetUniqueID();
}

/// <summary>
/// Removes the UniqueID from the list.
/// </summary>
~SevenZipBase()
{
// This lock probably isn't necessary but just in case...
lock (Identifiers)
{
Identifiers.Remove(_uniqueID);
}
}

/// <summary>
/// Gets or sets the archive password
/// </summary>
Expand Down

0 comments on commit c9f61f4

Please sign in to comment.