CancellationTokenSource.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #if NET_4_0 || BOOTSTRAP_NET_4_0
  2. //
  3. // CancellationTokenSource.cs
  4. //
  5. // Author:
  6. // Jérémie "Garuma" Laval <[email protected]>
  7. //
  8. // Copyright (c) 2009 Jérémie "Garuma" Laval
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11. // of this software and associated documentation files (the "Software"), to deal
  12. // in the Software without restriction, including without limitation the rights
  13. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. // copies of the Software, and to permit persons to whom the Software is
  15. // furnished to do so, subject to the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be included in
  18. // all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. // THE SOFTWARE.
  27. using System;
  28. using System.Collections.Generic;
  29. namespace System.Threading
  30. {
  31. public sealed class CancellationTokenSource : IDisposable
  32. {
  33. volatile bool canceled;
  34. volatile bool processed;
  35. int currId = int.MinValue;
  36. Dictionary<CancellationTokenRegistration, Action> callbacks
  37. = new Dictionary<CancellationTokenRegistration, Action> ();
  38. ManualResetEvent handle = new ManualResetEvent (false);
  39. object syncRoot = new object ();
  40. internal static readonly CancellationTokenSource NoneSource = new CancellationTokenSource ();
  41. public void Cancel ()
  42. {
  43. Cancel (false);
  44. }
  45. // If parameter is true we throw exception as soon as they appear otherwise we aggregate them
  46. public void Cancel (bool throwOnFirst)
  47. {
  48. canceled = true;
  49. handle.Set ();
  50. List<Exception> exceptions = null;
  51. if (!throwOnFirst)
  52. exceptions = new List<Exception> ();
  53. lock (callbacks) {
  54. foreach (KeyValuePair<CancellationTokenRegistration, Action> item in callbacks) {
  55. if (throwOnFirst) {
  56. item.Value ();
  57. } else {
  58. try {
  59. item.Value ();
  60. } catch (Exception e) {
  61. exceptions.Add (e);
  62. }
  63. }
  64. }
  65. }
  66. processed = true;
  67. if (exceptions != null && exceptions.Count > 0)
  68. throw new AggregateException (exceptions);
  69. }
  70. public void Dispose ()
  71. {
  72. }
  73. public static CancellationTokenSource CreateLinkedTokenSource (CancellationToken token1, CancellationToken token2)
  74. {
  75. return CreateLinkedTokenSource (new CancellationToken[] { token1, token2 });
  76. }
  77. public static CancellationTokenSource CreateLinkedTokenSource (params CancellationToken[] tokens)
  78. {
  79. CancellationTokenSource src = new CancellationTokenSource ();
  80. Action action = src.Cancel;
  81. foreach (CancellationToken token in tokens)
  82. token.Register (action);
  83. return src;
  84. }
  85. public CancellationToken Token {
  86. get {
  87. return CreateToken ();
  88. }
  89. }
  90. public bool IsCancellationRequested {
  91. get {
  92. return canceled;
  93. }
  94. }
  95. internal WaitHandle WaitHandle {
  96. get {
  97. return handle;
  98. }
  99. }
  100. internal CancellationTokenRegistration Register (Action callback, bool useSynchronizationContext)
  101. {
  102. CancellationTokenRegistration tokenReg = GetTokenReg ();
  103. if (canceled) {
  104. callback ();
  105. } else {
  106. bool temp = false;
  107. lock (syncRoot) {
  108. if (!(temp = canceled))
  109. callbacks.Add (tokenReg, callback);
  110. }
  111. if (temp)
  112. callback ();
  113. }
  114. return tokenReg;
  115. }
  116. internal void RemoveCallback (CancellationTokenRegistration tokenReg)
  117. {
  118. if (!canceled) {
  119. lock (syncRoot) {
  120. if (!canceled) {
  121. callbacks.Remove (tokenReg);
  122. return;
  123. }
  124. }
  125. }
  126. SpinWait sw = new SpinWait ();
  127. while (!processed)
  128. sw.SpinOnce ();
  129. }
  130. internal void ThrowIfCancellationRequested ()
  131. {
  132. if (canceled)
  133. throw new OperationCanceledException (CreateToken ());
  134. }
  135. CancellationTokenRegistration GetTokenReg ()
  136. {
  137. CancellationTokenRegistration registration
  138. = new CancellationTokenRegistration (Interlocked.Increment (ref currId), this);
  139. return registration;
  140. }
  141. CancellationToken CreateToken ()
  142. {
  143. CancellationToken tk = new CancellationToken (canceled);
  144. tk.Source = this;
  145. return tk;
  146. }
  147. }
  148. }
  149. #endif