AsyncLock.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. #nullable disable
  5. using System.Collections.Generic;
  6. namespace System.Reactive.Concurrency
  7. {
  8. /// <summary>
  9. /// Asynchronous lock.
  10. /// </summary>
  11. public sealed class AsyncLock : IDisposable
  12. {
  13. private bool _isAcquired;
  14. private bool _hasFaulted;
  15. private readonly object _guard = new object();
  16. private Queue<(Action<Delegate, object> action, Delegate @delegate, object state)> _queue;
  17. /// <summary>
  18. /// Queues the action for execution. If the caller acquires the lock and becomes the owner,
  19. /// the queue is processed. If the lock is already owned, the action is queued and will get
  20. /// processed by the owner.
  21. /// </summary>
  22. /// <param name="action">Action to queue for execution.</param>
  23. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  24. public void Wait(Action action)
  25. {
  26. if (action == null)
  27. {
  28. throw new ArgumentNullException(nameof(action));
  29. }
  30. Wait(action, static closureAction => closureAction());
  31. }
  32. /// <summary>
  33. /// Queues the action for execution. If the caller acquires the lock and becomes the owner,
  34. /// the queue is processed. If the lock is already owned, the action is queued and will get
  35. /// processed by the owner.
  36. /// </summary>
  37. /// <param name="action">Action to queue for execution.</param>
  38. /// <param name="state">The state to pass to the action when it gets invoked under the lock.</param>
  39. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  40. /// <remarks>In case TState is a value type, this operation will involve boxing of <paramref name="state"/>.
  41. /// However, this is often an improvement over the allocation of a closure object and a delegate.</remarks>
  42. internal void Wait<TState>(TState state, Action<TState> action)
  43. {
  44. if (action == null)
  45. {
  46. throw new ArgumentNullException(nameof(action));
  47. }
  48. Wait(state, action, static (actionObject, stateObject) => ((Action<TState>)actionObject)((TState)stateObject));
  49. }
  50. private void Wait(object state, Delegate @delegate, Action<Delegate, object> action)
  51. {
  52. // allow one thread to update the state
  53. lock (_guard)
  54. {
  55. // if a previous action crashed, ignore any future actions
  56. if (_hasFaulted)
  57. {
  58. return;
  59. }
  60. // if the "lock" is busy, queue up the extra work
  61. // otherwise there is no need to queue up "action"
  62. if (_isAcquired)
  63. {
  64. // create the queue if necessary
  65. var q = _queue;
  66. if (q == null)
  67. {
  68. q = new Queue<(Action<Delegate, object> action, Delegate @delegate, object state)>();
  69. _queue = q;
  70. }
  71. // enqueue the work
  72. q.Enqueue((action, @delegate, state));
  73. return;
  74. }
  75. // indicate there is processing going on
  76. _isAcquired = true;
  77. }
  78. // if we get here, execute the "action" first
  79. for (; ; )
  80. {
  81. try
  82. {
  83. action(@delegate, state);
  84. }
  85. catch
  86. {
  87. // the execution failed, terminate this AsyncLock
  88. lock (_guard)
  89. {
  90. // throw away the queue
  91. _queue = null;
  92. // report fault
  93. _hasFaulted = true;
  94. }
  95. throw;
  96. }
  97. // execution succeeded, let's see if more work has to be done
  98. lock (_guard)
  99. {
  100. var q = _queue;
  101. // either there is no queue yet or we run out of work
  102. if (q == null || q.Count == 0)
  103. {
  104. // release the lock
  105. _isAcquired = false;
  106. return;
  107. }
  108. // get the next work action
  109. (action, @delegate, state) = q.Dequeue();
  110. }
  111. // loop back and execute the action
  112. }
  113. }
  114. /// <summary>
  115. /// Clears the work items in the queue and drops further work being queued.
  116. /// </summary>
  117. public void Dispose()
  118. {
  119. lock (_guard)
  120. {
  121. _queue = null;
  122. _hasFaulted = true;
  123. }
  124. }
  125. }
  126. }