From 56c81c01351ef05c8b3643bc52d4a44b5b2cd28b Mon Sep 17 00:00:00 2001 From: Kim Tisott Date: Tue, 7 Jun 2022 22:16:05 -0300 Subject: [PATCH] Added thread safe operations in ObjectPool --- LemonUI/ObjectPool.cs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/LemonUI/ObjectPool.cs b/LemonUI/ObjectPool.cs index a106c465..45e19489 100644 --- a/LemonUI/ObjectPool.cs +++ b/LemonUI/ObjectPool.cs @@ -13,7 +13,7 @@ using GTA.UI; #endif using System; -using System.Collections.Generic; +using System.Collections.Concurrent; using System.Drawing; namespace LemonUI @@ -106,7 +106,7 @@ public class ObjectPool /// /// The list of processable objects. /// - private readonly List objects = new List(); + private readonly ConcurrentDictionary objects = new ConcurrentDictionary(); #endregion @@ -120,7 +120,7 @@ public bool AreAnyVisible get { // Iterate over the objects - foreach (IProcessable obj in objects) + foreach (IProcessable obj in objects.Values) { // If is visible return true if (obj.Visible) @@ -221,12 +221,13 @@ public void Add(IProcessable obj) throw new ArgumentNullException(nameof(obj)); } + int key = obj.GetHashCode(); // Otherwise, add it to the general pool - if (objects.Contains(obj)) + if (objects.ContainsKey(key)) { throw new InvalidOperationException("The object is already part of this pool."); } - objects.Add(obj); + objects.TryAdd(key, obj); } /// /// Removes the object from the pool. @@ -234,7 +235,7 @@ public void Add(IProcessable obj) /// The object to remove. public void Remove(IProcessable obj) { - objects.Remove(obj); + objects.TryRemove(obj.GetHashCode(), out _); } /// /// Performs the specified action on each element that matches T. @@ -243,7 +244,7 @@ public void Remove(IProcessable obj) /// The action delegate to perform on each T. public void ForEach(Action action) { - foreach (IProcessable obj in objects) + foreach (IProcessable obj in objects.Values) { if (obj is T conv) { @@ -257,7 +258,7 @@ public void ForEach(Action action) public void RefreshAll() { // Iterate over the objects and recalculate those possible - foreach (IProcessable obj in objects) + foreach (IProcessable obj in objects.Values) { if (obj is IRecalculable recal) { @@ -270,7 +271,7 @@ public void RefreshAll() /// public void HideAll() { - foreach (IProcessable obj in objects) + foreach (IProcessable obj in objects.Values) { obj.Visible = false; } @@ -285,7 +286,7 @@ public void Process() DetectResolutionChanges(); DetectSafezoneChanges(); // And process the objects in the pool - foreach (IProcessable obj in objects) + foreach (IProcessable obj in objects.Values) { obj.Process(); }