From c9f61f476d750c3f8e7038cf7f906a8b5d6c2aee Mon Sep 17 00:00:00 2001 From: Pavel Vorozheykin Date: Tue, 12 Apr 2022 21:38:38 +0300 Subject: [PATCH] Calculate UniqueID via increment 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. --- SevenZip/SevenZipBase.cs | 32 +++----------------------------- 1 file changed, 3 insertions(+), 29 deletions(-) diff --git a/SevenZip/SevenZipBase.cs b/SevenZip/SevenZipBase.cs index 3d72e6f..540303e 100644 --- a/SevenZip/SevenZipBase.cs +++ b/SevenZip/SevenZipBase.cs @@ -15,7 +15,7 @@ public abstract class SevenZipBase : MarshalByRefObject { private readonly bool _reportErrors; private readonly int _uniqueID; - private static readonly List Identifiers = new List(); + private static int _incrementingUniqueId = int.MinValue; /// /// True if the instance of the class needs to be recreated in new thread context; otherwise, false. @@ -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; } /// @@ -132,18 +118,6 @@ protected SevenZipBase(string password = "") _uniqueID = GetUniqueID(); } - /// - /// Removes the UniqueID from the list. - /// - ~SevenZipBase() - { - // This lock probably isn't necessary but just in case... - lock (Identifiers) - { - Identifiers.Remove(_uniqueID); - } - } - /// /// Gets or sets the archive password ///