ThreadNeutralSemaphore.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.Runtime
  5. {
  6. using System.Collections.Generic;
  7. using System.Threading;
  8. using System.Globalization;
  9. using System.Diagnostics.CodeAnalysis;
  10. using System.Diagnostics;
  11. [Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.PrivatePrimitive,
  12. SupportsAsync = true, ReleaseMethod = "Exit")]
  13. class ThreadNeutralSemaphore
  14. {
  15. #if DEBUG
  16. StackTrace exitStack;
  17. #endif
  18. static Action<object, TimeoutException> enteredAsyncCallback;
  19. bool aborted;
  20. Func<Exception> abortedExceptionGenerator;
  21. int count;
  22. int maxCount;
  23. [Fx.Tag.SynchronizationObject(Blocking = false)]
  24. object ThisLock = new object();
  25. [Fx.Tag.SynchronizationObject]
  26. Queue<AsyncWaitHandle> waiters;
  27. public ThreadNeutralSemaphore(int maxCount)
  28. : this(maxCount, null)
  29. {
  30. }
  31. public ThreadNeutralSemaphore(int maxCount, Func<Exception> abortedExceptionGenerator)
  32. {
  33. Fx.Assert(maxCount > 0, "maxCount must be positive");
  34. this.maxCount = maxCount;
  35. this.abortedExceptionGenerator = abortedExceptionGenerator;
  36. }
  37. static Action<object, TimeoutException> EnteredAsyncCallback
  38. {
  39. get
  40. {
  41. if (enteredAsyncCallback == null)
  42. {
  43. enteredAsyncCallback = new Action<object, TimeoutException>(OnEnteredAsync);
  44. }
  45. return enteredAsyncCallback;
  46. }
  47. }
  48. Queue<AsyncWaitHandle> Waiters
  49. {
  50. get
  51. {
  52. if (this.waiters == null)
  53. {
  54. this.waiters = new Queue<AsyncWaitHandle>();
  55. }
  56. return this.waiters;
  57. }
  58. }
  59. public bool EnterAsync(TimeSpan timeout, FastAsyncCallback callback, object state)
  60. {
  61. Fx.Assert(callback != null, "must have a non-null call back for async purposes");
  62. AsyncWaitHandle waiter = null;
  63. lock (this.ThisLock)
  64. {
  65. if (this.aborted)
  66. {
  67. throw Fx.Exception.AsError(CreateObjectAbortedException());
  68. }
  69. if (this.count < this.maxCount)
  70. {
  71. this.count++;
  72. return true;
  73. }
  74. waiter = new AsyncWaitHandle();
  75. this.Waiters.Enqueue(waiter);
  76. }
  77. return waiter.WaitAsync(EnteredAsyncCallback, new EnterAsyncData(this, waiter, callback, state), timeout);
  78. }
  79. static void OnEnteredAsync(object state, TimeoutException exception)
  80. {
  81. EnterAsyncData data = (EnterAsyncData)state;
  82. ThreadNeutralSemaphore thisPtr = data.Semaphore;
  83. Exception exceptionToPropagate = exception;
  84. if (exception != null)
  85. {
  86. if (!thisPtr.RemoveWaiter(data.Waiter))
  87. {
  88. // The timeout ----d with Exit and exit won.
  89. // We've successfully entered.
  90. exceptionToPropagate = null;
  91. }
  92. }
  93. Fx.Assert(!thisPtr.waiters.Contains(data.Waiter), "The waiter should have been removed already.");
  94. if (thisPtr.aborted)
  95. {
  96. exceptionToPropagate = thisPtr.CreateObjectAbortedException();
  97. }
  98. data.Callback(data.State, exceptionToPropagate);
  99. }
  100. public bool TryEnter()
  101. {
  102. lock (this.ThisLock)
  103. {
  104. if (this.count < this.maxCount)
  105. {
  106. this.count++;
  107. return true;
  108. }
  109. return false;
  110. }
  111. }
  112. [Fx.Tag.Blocking(CancelMethod = "Abort")]
  113. public void Enter(TimeSpan timeout)
  114. {
  115. if (!TryEnter(timeout))
  116. {
  117. throw Fx.Exception.AsError(CreateEnterTimedOutException(timeout));
  118. }
  119. }
  120. [Fx.Tag.Blocking(CancelMethod = "Abort")]
  121. public bool TryEnter(TimeSpan timeout)
  122. {
  123. AsyncWaitHandle waiter = EnterCore();
  124. if (waiter != null)
  125. {
  126. bool timedOut = !waiter.Wait(timeout);
  127. if (this.aborted)
  128. {
  129. throw Fx.Exception.AsError(CreateObjectAbortedException());
  130. }
  131. if (timedOut && !RemoveWaiter(waiter))
  132. {
  133. // The timeout ----d with Exit and exit won.
  134. // We've successfully entered.
  135. timedOut = false;
  136. }
  137. return !timedOut;
  138. }
  139. return true;
  140. }
  141. internal static TimeoutException CreateEnterTimedOutException(TimeSpan timeout)
  142. {
  143. return new TimeoutException(InternalSR.LockTimeoutExceptionMessage(timeout));
  144. }
  145. Exception CreateObjectAbortedException()
  146. {
  147. if (this.abortedExceptionGenerator != null)
  148. {
  149. return this.abortedExceptionGenerator();
  150. }
  151. else
  152. {
  153. return new OperationCanceledException(InternalSR.ThreadNeutralSemaphoreAborted);
  154. }
  155. }
  156. // remove a waiter from our queue. Returns true if successful. Used to implement timeouts.
  157. bool RemoveWaiter(AsyncWaitHandle waiter)
  158. {
  159. bool removed = false;
  160. lock (this.ThisLock)
  161. {
  162. for (int i = this.Waiters.Count; i > 0; i--)
  163. {
  164. AsyncWaitHandle temp = this.Waiters.Dequeue();
  165. if (object.ReferenceEquals(temp, waiter))
  166. {
  167. removed = true;
  168. }
  169. else
  170. {
  171. this.Waiters.Enqueue(temp);
  172. }
  173. }
  174. }
  175. return removed;
  176. }
  177. AsyncWaitHandle EnterCore()
  178. {
  179. AsyncWaitHandle waiter;
  180. lock (this.ThisLock)
  181. {
  182. if (this.aborted)
  183. {
  184. throw Fx.Exception.AsError(CreateObjectAbortedException());
  185. }
  186. if (this.count < this.maxCount)
  187. {
  188. this.count++;
  189. return null;
  190. }
  191. waiter = new AsyncWaitHandle();
  192. this.Waiters.Enqueue(waiter);
  193. }
  194. return waiter;
  195. }
  196. public int Exit()
  197. {
  198. AsyncWaitHandle waiter;
  199. int remainingCount = -1;
  200. lock (this.ThisLock)
  201. {
  202. if (this.aborted)
  203. {
  204. return remainingCount;
  205. }
  206. if (this.count == 0)
  207. {
  208. string message = InternalSR.InvalidSemaphoreExit;
  209. #if DEBUG
  210. if (!Fx.FastDebug && exitStack != null)
  211. {
  212. string originalStack = exitStack.ToString().Replace("\r\n", "\r\n ");
  213. message = string.Format(CultureInfo.InvariantCulture,
  214. "Object synchronization method was called from an unsynchronized block of code. Previous Exit(): {0}", originalStack);
  215. }
  216. #endif
  217. throw Fx.Exception.AsError(new SynchronizationLockException(message));
  218. }
  219. if (this.waiters == null || this.waiters.Count == 0)
  220. {
  221. this.count--;
  222. #if DEBUG
  223. if (!Fx.FastDebug && this.count == 0)
  224. {
  225. exitStack = new StackTrace();
  226. }
  227. #endif
  228. return this.count;
  229. }
  230. waiter = this.waiters.Dequeue();
  231. remainingCount = this.count;
  232. }
  233. waiter.Set();
  234. return remainingCount;
  235. }
  236. // Abort the ThreadNeutralSemaphore object.
  237. public void Abort()
  238. {
  239. lock (this.ThisLock)
  240. {
  241. if (this.aborted)
  242. {
  243. return;
  244. }
  245. this.aborted = true;
  246. if (this.waiters != null)
  247. {
  248. while (this.waiters.Count > 0)
  249. {
  250. AsyncWaitHandle waiter = this.waiters.Dequeue();
  251. waiter.Set();
  252. }
  253. }
  254. }
  255. }
  256. class EnterAsyncData
  257. {
  258. public EnterAsyncData(ThreadNeutralSemaphore semaphore, AsyncWaitHandle waiter, FastAsyncCallback callback, object state)
  259. {
  260. this.Waiter = waiter;
  261. this.Semaphore = semaphore;
  262. this.Callback = callback;
  263. this.State = state;
  264. }
  265. public ThreadNeutralSemaphore Semaphore
  266. {
  267. get;
  268. set;
  269. }
  270. public AsyncWaitHandle Waiter
  271. {
  272. get;
  273. set;
  274. }
  275. public FastAsyncCallback Callback
  276. {
  277. get;
  278. set;
  279. }
  280. public object State
  281. {
  282. get;
  283. set;
  284. }
  285. }
  286. }
  287. }