Skip to content

Instantly share code, notes, and snippets.

@SchreinerK
Last active July 3, 2019 08:08
Show Gist options
  • Save SchreinerK/cd0926b805d239d6ab72f26e0767e0df to your computer and use it in GitHub Desktop.
Save SchreinerK/cd0926b805d239d6ab72f26e0767e0df to your computer and use it in GitHub Desktop.
Guid Ressource Lock
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