Skip to content

Instantly share code, notes, and snippets.

@NamelessG0d
Created June 9, 2023 02:21
Show Gist options
  • Save NamelessG0d/c50f89426f77e3a3d1b333efab25a2f5 to your computer and use it in GitHub Desktop.
Save NamelessG0d/c50f89426f77e3a3d1b333efab25a2f5 to your computer and use it in GitHub Desktop.
ConcurrentBag that uses ConcurrentDictionary wtih ManualResetEventSlim to allow to wait on removal of a specific item
public class ConcurrentWaitableBag<T> where T : notnull
{
private ConcurrentDictionary<T, ManualResetEventSlim> dict = new ConcurrentDictionary<T, ManualResetEventSlim>();
public bool TryAdd(T item)
{
var semaphore = new ManualResetEventSlim(false);
return dict.TryAdd(item, semaphore);
}
public bool TryRemove(T item)
{
if (dict.TryRemove(item, out var manualResetEvent))
{
manualResetEvent.Set();
manualResetEvent.Dispose();
return true;
}
return false;
}
public ManualResetEventSlim? GetRemoveEvent(T item)
{
if (dict.TryGetValue(item, out var manualResetEvent))
{
return manualResetEvent;
}
return null;
}
public bool ContainsKey(T item) => dict.ContainsKey(item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment