AsyncGate.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Reactive.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Threading
  8. {
  9. public sealed class AsyncGate : IAsyncGate
  10. {
  11. private readonly object _gate = new();
  12. private readonly SemaphoreSlim _semaphore = new(1, 1);
  13. private readonly AsyncLocal<int> _recursionCount = new();
  14. public ValueTask<AsyncGateReleaser> LockAsync()
  15. {
  16. var shouldAcquire = false;
  17. lock (_gate)
  18. {
  19. if (_recursionCount.Value == 0)
  20. {
  21. shouldAcquire = true;
  22. _recursionCount.Value = 1;
  23. }
  24. else
  25. {
  26. _recursionCount.Value++;
  27. }
  28. }
  29. if (shouldAcquire)
  30. {
  31. return new ValueTask<AsyncGateReleaser>(_semaphore.WaitAsync().ContinueWith(_ => new AsyncGateReleaser(this)));
  32. }
  33. return new ValueTask<AsyncGateReleaser>(new AsyncGateReleaser(this));
  34. }
  35. void IAsyncGate.Release()
  36. {
  37. lock (_gate)
  38. {
  39. Debug.Assert(_recursionCount.Value > 0);
  40. if (--_recursionCount.Value == 0)
  41. {
  42. _semaphore.Release();
  43. }
  44. }
  45. }
  46. }
  47. }