Created
June 9, 2023 02:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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