AsyncLock.cs 5.0 KB

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