TaskExt.cs 5.5 KB

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