TaskExt.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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.InnerExceptions);
  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 Then<T>(this Task<T> task, Action<Task<T>> continuation)
  56. {
  57. //
  58. // Central location to deal with continuations; allows for experimentation with flags.
  59. // Note that right now, we don't go for synchronous execution. Users can block on the
  60. // task returned from MoveNext, which can cause deadlocks (e.g. typical uses of GroupBy
  61. // involve some aggregate). We'd need deeper asynchrony to make this work with less
  62. // spawning of tasks.
  63. //
  64. return task.ContinueWith(continuation);
  65. }
  66. public static Task<R> Then<T, R>(this Task<T> task, Func<Task<T>, R> continuation)
  67. {
  68. //
  69. // See comment on Then<T> for rationale.
  70. //
  71. return task.ContinueWith(continuation);
  72. }
  73. public static Task<bool> UsingEnumerator(this Task<bool> task, IDisposable disposable)
  74. {
  75. return task.Finally(() =>
  76. {
  77. if (task.IsFaulted || task.IsCanceled || !task.Result)
  78. disposable.Dispose();
  79. });
  80. }
  81. public static Task<R> Finally<R>(this Task<R> task, Action action)
  82. {
  83. var tcs = new TaskCompletionSource<R>();
  84. task.ContinueWith(t =>
  85. {
  86. try
  87. {
  88. action();
  89. }
  90. finally
  91. {
  92. switch (t.Status)
  93. {
  94. case TaskStatus.Canceled:
  95. tcs.SetCanceled();
  96. break;
  97. case TaskStatus.Faulted:
  98. tcs.SetException(t.Exception.InnerException);
  99. break;
  100. case TaskStatus.RanToCompletion:
  101. tcs.SetResult(t.Result);
  102. break;
  103. }
  104. }
  105. }, TaskContinuationOptions.ExecuteSynchronously);
  106. return tcs.Task;
  107. }
  108. public static Task<V> Zip<T, U, V>(this Task<T> t1, Task<U> t2, Func<T, U, V> f)
  109. {
  110. var gate = new object();
  111. var tcs = new TaskCompletionSource<V>();
  112. var i = 2;
  113. var complete = new Action<Task>(t =>
  114. {
  115. if (Interlocked.Decrement(ref i) == 0)
  116. {
  117. var exs = new List<Exception>();
  118. if (t1.IsFaulted)
  119. exs.Add(t1.Exception);
  120. if (t2.IsFaulted)
  121. exs.Add(t2.Exception);
  122. if (exs.Count > 0)
  123. tcs.TrySetException(exs);
  124. else if (t1.IsCanceled || t2.IsCanceled)
  125. tcs.TrySetCanceled();
  126. else
  127. {
  128. var res = default(V);
  129. try
  130. {
  131. res = f(t1.Result, t2.Result);
  132. }
  133. catch (Exception ex)
  134. {
  135. tcs.TrySetException(ex);
  136. return;
  137. }
  138. tcs.TrySetResult(res);
  139. }
  140. }
  141. });
  142. t1.ContinueWith(complete);
  143. t2.ContinueWith(complete);
  144. return tcs.Task;
  145. }
  146. }
  147. }