Skip to content

Instantly share code, notes, and snippets.

@mlehmk
Created March 4, 2016 11:12
Show Gist options
  • Select an option

  • Save mlehmk/e215f00dc4d1aeee71b4 to your computer and use it in GitHub Desktop.

Select an option

Save mlehmk/e215f00dc4d1aeee71b4 to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
using System.Threading;
namespace CustomNamespace
{
public class Guard
{
private SemaphoreSlim _semaphore = new SemaphoreSlim(1);
private class Disposable : IDisposable
{
private SemaphoreSlim _semaphore;
public Disposable(SemaphoreSlim semaphore)
{
_semaphore = semaphore;
}
void IDisposable.Dispose()
{
_semaphore?.Release();
_semaphore = null;
}
}
public TaskAwaiter<IDisposable> GetAwaiter()
{
return _semaphore.WaitAsync().ContinueWith(o => (IDisposable)new Disposable(_semaphore)).GetAwaiter();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment