1
0

TaskExt.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace System.Threading.Tasks
  6. {
  7. static class TaskExt
  8. {
  9. public static readonly Task<bool> True;
  10. public static readonly Task<bool> False;
  11. static TaskExt()
  12. {
  13. True = Return(true);
  14. False = Return(false);
  15. }
  16. public static Task<T> Return<T>(T value)
  17. {
  18. var tcs = new TaskCompletionSource<T>();
  19. tcs.TrySetResult(value);
  20. return tcs.Task;
  21. }
  22. public static Task<T> Throw<T>(Exception exception)
  23. {
  24. var tcs = new TaskCompletionSource<T>();
  25. tcs.TrySetException(exception);
  26. return tcs.Task;
  27. }
  28. public static void Handle<T, R>(this Task<T> task, TaskCompletionSource<R> tcs, Action<T> success)
  29. {
  30. if (task.IsFaulted)
  31. tcs.TrySetException(task.Exception);
  32. else if (task.IsCanceled)
  33. tcs.TrySetCanceled();
  34. else if (task.IsCompleted)
  35. success(task.Result);
  36. }
  37. public static void Handle<T, R>(this Task<T> task, TaskCompletionSource<R> tcs, Action<T> success, Action<AggregateException> error)
  38. {
  39. if (task.IsFaulted)
  40. error(task.Exception);
  41. else if (task.IsCanceled)
  42. tcs.TrySetCanceled();
  43. else if (task.IsCompleted)
  44. success(task.Result);
  45. }
  46. public static void Handle<T, R>(this Task<T> task, TaskCompletionSource<R> tcs, Action<T> success, Action<AggregateException> error, Action canceled)
  47. {
  48. if (task.IsFaulted)
  49. error(task.Exception);
  50. else if (task.IsCanceled)
  51. canceled();
  52. else if (task.IsCompleted)
  53. success(task.Result);
  54. }
  55. public static Task<bool> UsingEnumerator(this Task<bool> task, IDisposable disposable)
  56. {
  57. task.ContinueWith(t =>
  58. {
  59. if (t.IsFaulted)
  60. {
  61. var ignored = t.Exception; // don't remove!
  62. }
  63. if (t.IsFaulted || t.IsCanceled || !t.Result)
  64. disposable.Dispose();
  65. }, TaskContinuationOptions.ExecuteSynchronously);
  66. return task;
  67. }
  68. public static Task Then<T>(this Task<T> task, Action<Task<T>> continuation)
  69. {
  70. //
  71. // Central location to deal with continuations; allows for experimentation with flags.
  72. // Note that right now, we don't go for synchronous execution. Users can block on the
  73. // task returned from MoveNext, which can cause deadlocks (e.g. typical uses of GroupBy
  74. // involve some aggregate). We'd need deeper asynchrony to make this work with less
  75. // spawning of tasks.
  76. //
  77. return task.ContinueWith(continuation);
  78. }
  79. public static Task<R> Then<T, R>(this Task<T> task, Func<Task<T>, R> continuation)
  80. {
  81. //
  82. // See comment on Then<T> for rationale.
  83. //
  84. return task.ContinueWith(continuation);
  85. }
  86. public static Task<bool> UsingEnumeratorSync(this Task<bool> task, IDisposable disposable)
  87. {
  88. var tcs = new TaskCompletionSource<bool>();
  89. task.ContinueWith(t =>
  90. {
  91. if (t.IsFaulted || t.IsCanceled || !t.Result)
  92. disposable.Dispose(); // TODO: Check whether we need exception handling here!
  93. t.Handle(tcs, res => tcs.TrySetResult(res));
  94. }, TaskContinuationOptions.ExecuteSynchronously);
  95. return tcs.Task;
  96. }
  97. public static Task<R> Finally<R>(this Task<R> task, Action action)
  98. {
  99. var tcs = new TaskCompletionSource<R>();
  100. task.ContinueWith(t =>
  101. {
  102. try
  103. {
  104. action();
  105. }
  106. finally
  107. {
  108. switch (t.Status)
  109. {
  110. case TaskStatus.Canceled:
  111. tcs.SetCanceled();
  112. break;
  113. case TaskStatus.Faulted:
  114. tcs.SetException(t.Exception.InnerException);
  115. break;
  116. case TaskStatus.RanToCompletion:
  117. tcs.SetResult(t.Result);
  118. break;
  119. }
  120. }
  121. }, TaskContinuationOptions.ExecuteSynchronously);
  122. return tcs.Task;
  123. }
  124. public static Task<V> Zip<T, U, V>(this Task<T> t1, Task<U> t2, Func<T, U, V> f)
  125. {
  126. var gate = new object();
  127. var tcs = new TaskCompletionSource<V>();
  128. var i = 2;
  129. var complete = new Action<Task>(t =>
  130. {
  131. if (Interlocked.Decrement(ref i) == 0)
  132. {
  133. var exs = new List<Exception>();
  134. if (t1.IsFaulted)
  135. exs.Add(t1.Exception);
  136. if (t2.IsFaulted)
  137. exs.Add(t2.Exception);
  138. if (exs.Count > 0)
  139. tcs.TrySetException(exs);
  140. else if (t1.IsCanceled || t2.IsCanceled)
  141. tcs.TrySetCanceled();
  142. else
  143. {
  144. var res = default(V);
  145. try
  146. {
  147. res = f(t1.Result, t2.Result);
  148. }
  149. catch (Exception ex)
  150. {
  151. tcs.TrySetException(ex);
  152. return;
  153. }
  154. tcs.TrySetResult(res);
  155. }
  156. }
  157. });
  158. t1.ContinueWith(complete);
  159. t2.ContinueWith(complete);
  160. return tcs.Task;
  161. }
  162. }
  163. }