Last active
July 3, 2019 08:08
-
-
Save SchreinerK/cd0926b805d239d6ab72f26e0767e0df to your computer and use it in GitHub Desktop.
Guid Ressource Lock
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 sealed class GuidSemaphoreSlim : IDisposable | |
{ | |
private static readonly Dictionary<Guid,SemaphoreSlim> Handles=new Dictionary<Guid, SemaphoreSlim>(); | |
private readonly Guid _guid; | |
private readonly SemaphoreSlim _semaphore; | |
/// <summary> | |
/// Usage: using(await GuidSemaphoreSlim.WaitAsync(myGuid)) {...} | |
/// </summary> | |
public static async Task<IDisposable> WaitAsync(Guid guid) | |
{ | |
var waitHandle = new GuidLock(guid); | |
await waitHandle._semaphore.WaitAsync(); | |
return waitHandle; | |
} | |
private GuidSemaphoreSlim(Guid guid) | |
{ | |
_guid = guid; | |
lock (Handles) | |
{ | |
if (!Handles.TryGetValue(_guid, out _semaphore)) | |
{ | |
_semaphore = new SemaphoreSlim(1, 1); | |
Handles.Add(_guid, _semaphore); | |
} | |
} | |
} | |
public Task WaitAsync() | |
{ | |
return _semaphore.WaitAsync(); | |
} | |
public void Release() | |
{ | |
_semaphore.Release(); | |
} | |
void IDisposable.Dispose() | |
{ | |
_semaphore.Release(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment