Skip to content

Commit

Permalink
Merge pull request #65 from KimTisott/master
Browse files Browse the repository at this point in the history
Added thread safe operations in ObjectPool
  • Loading branch information
justalemon committed Jun 8, 2022
2 parents b0df662 + 12243b3 commit f79517f
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions LemonUI/ObjectPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
using GTA.UI;
#endif
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Drawing;

namespace LemonUI
Expand Down Expand Up @@ -106,7 +106,7 @@ public class ObjectPool
/// <summary>
/// The list of processable objects.
/// </summary>
private readonly List<IProcessable> objects = new List<IProcessable>();
private readonly ConcurrentDictionary<int, IProcessable> objects = new ConcurrentDictionary<int, IProcessable>();

#endregion

Expand All @@ -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)
Expand Down Expand Up @@ -221,20 +221,21 @@ 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);
}
/// <summary>
/// Removes the object from the pool.
/// </summary>
/// <param name="obj">The object to remove.</param>
public void Remove(IProcessable obj)
{
objects.Remove(obj);
objects.TryRemove(obj.GetHashCode(), out _);
}
/// <summary>
/// Performs the specified action on each element that matches T.
Expand All @@ -243,7 +244,7 @@ public void Remove(IProcessable obj)
/// <param name="action">The action delegate to perform on each T.</param>
public void ForEach<T>(Action<T> action)
{
foreach (IProcessable obj in objects)
foreach (IProcessable obj in objects.Values)
{
if (obj is T conv)
{
Expand All @@ -257,7 +258,7 @@ public void ForEach<T>(Action<T> 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)
{
Expand All @@ -270,7 +271,7 @@ public void RefreshAll()
/// </summary>
public void HideAll()
{
foreach (IProcessable obj in objects)
foreach (IProcessable obj in objects.Values)
{
obj.Visible = false;
}
Expand All @@ -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();
}
Expand Down

0 comments on commit f79517f

Please sign in to comment.