CancellationTokenSource.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 class CancellationTokenSource : IDisposable, ICancelableOperation
  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. //#if USE_MONITOR
  40. object syncRoot = new object ();
  41. //#endif
  42. public void Cancel ()
  43. {
  44. Cancel (false);
  45. }
  46. // If parameter is true we throw exception as soon as they appear otherwise we aggregate them
  47. public void Cancel (bool throwOnFirst)
  48. {
  49. canceled = true;
  50. handle.Set ();
  51. List<Exception> exceptions = null;
  52. if (!throwOnFirst)
  53. exceptions = new List<Exception> ();
  54. lock (callbacks) {
  55. foreach (KeyValuePair<CancellationTokenRegistration, Action> item in callbacks) {
  56. if (throwOnFirst) {
  57. item.Value ();
  58. } else {
  59. try {
  60. item.Value ();
  61. } catch (Exception e) {
  62. exceptions.Add (e);
  63. }
  64. }
  65. }
  66. }
  67. processed = true;
  68. if (exceptions != null && exceptions.Count > 0)
  69. throw new AggregateException (exceptions);
  70. }
  71. public void Dispose ()
  72. {
  73. }
  74. public static CancellationTokenSource CreateLinkedTokenSource (CancellationToken token1, CancellationToken token2)
  75. {
  76. return CreateLinkedTokenSource (new CancellationToken[] { token1, token2 });
  77. }
  78. public static CancellationTokenSource CreateLinkedTokenSource (params CancellationToken[] tokens)
  79. {
  80. CancellationTokenSource src = new CancellationTokenSource ();
  81. Action action = src.Cancel;
  82. foreach (CancellationToken token in tokens)
  83. token.Register (action);
  84. return src;
  85. }
  86. public CancellationToken Token {
  87. get {
  88. CancellationToken token = new CancellationToken (canceled);
  89. token.Source = this;
  90. return token;
  91. }
  92. }
  93. public bool IsCancellationRequested {
  94. get {
  95. return canceled;
  96. }
  97. }
  98. internal WaitHandle WaitHandle {
  99. get {
  100. return handle;
  101. }
  102. }
  103. internal CancellationTokenRegistration Register (Action callback, bool useSynchronizationContext)
  104. {
  105. CancellationTokenRegistration tokenReg = GetTokenReg ();
  106. if (canceled) {
  107. callback ();
  108. } else {
  109. bool temp = false;
  110. lock (syncRoot) {
  111. if (!(temp = canceled))
  112. callbacks.Add (tokenReg, callback);
  113. }
  114. if (temp)
  115. callback ();
  116. }
  117. return tokenReg;
  118. }
  119. internal void RemoveCallback (CancellationTokenRegistration tokenReg)
  120. {
  121. if (!canceled) {
  122. lock (syncRoot) {
  123. if (!canceled) {
  124. callbacks.Remove (tokenReg);
  125. return;
  126. }
  127. }
  128. }
  129. SpinWait sw = new SpinWait ();
  130. while (!processed)
  131. sw.SpinOnce ();
  132. }
  133. CancellationTokenRegistration GetTokenReg ()
  134. {
  135. CancellationTokenRegistration registration
  136. = new CancellationTokenRegistration (Interlocked.Increment (ref currId), this);
  137. return registration;
  138. }
  139. }
  140. }
  141. #endif