TaskExtensions.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // <copyright>
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. // </copyright>
  4. namespace System.Runtime
  5. {
  6. using System.Runtime.CompilerServices;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. internal static class TaskExtensions
  10. {
  11. public static IAsyncResult AsAsyncResult<T>(this Task<T> task, AsyncCallback callback, object state)
  12. {
  13. if (task == null)
  14. {
  15. throw Fx.Exception.ArgumentNull("task");
  16. }
  17. if (task.Status == TaskStatus.Created)
  18. {
  19. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.SFxTaskNotStarted));
  20. }
  21. var tcs = new TaskCompletionSource<T>(state);
  22. task.ContinueWith(
  23. t =>
  24. {
  25. if (t.IsFaulted)
  26. {
  27. tcs.TrySetException(t.Exception.InnerExceptions);
  28. }
  29. else if (t.IsCanceled)
  30. {
  31. // the use of Task.ContinueWith(,TaskContinuationOptions.OnlyOnRanToCompletion)
  32. // can give us a cancelled Task here with no t.Exception.
  33. tcs.TrySetCanceled();
  34. }
  35. else
  36. {
  37. tcs.TrySetResult(t.Result);
  38. }
  39. if (callback != null)
  40. {
  41. callback(tcs.Task);
  42. }
  43. },
  44. TaskContinuationOptions.ExecuteSynchronously);
  45. return tcs.Task;
  46. }
  47. public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
  48. {
  49. if (task == null)
  50. {
  51. throw Fx.Exception.ArgumentNull("task");
  52. }
  53. if (task.Status == TaskStatus.Created)
  54. {
  55. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.SFxTaskNotStarted));
  56. }
  57. var tcs = new TaskCompletionSource<object>(state);
  58. task.ContinueWith(
  59. t =>
  60. {
  61. if (t.IsFaulted)
  62. {
  63. tcs.TrySetException(t.Exception.InnerExceptions);
  64. }
  65. else if (t.IsCanceled)
  66. {
  67. // the use of Task.ContinueWith(,TaskContinuationOptions.OnlyOnRanToCompletion)
  68. // can give us a cancelled Task here with no t.Exception.
  69. tcs.TrySetCanceled();
  70. }
  71. else
  72. {
  73. tcs.TrySetResult(null);
  74. }
  75. if (callback != null)
  76. {
  77. callback(tcs.Task);
  78. }
  79. },
  80. TaskContinuationOptions.ExecuteSynchronously);
  81. return tcs.Task;
  82. }
  83. public static ConfiguredTaskAwaitable SuppressContextFlow(this Task task)
  84. {
  85. return task.ConfigureAwait(false);
  86. }
  87. public static ConfiguredTaskAwaitable<T> SuppressContextFlow<T>(this Task<T> task)
  88. {
  89. return task.ConfigureAwait(false);
  90. }
  91. public static ConfiguredTaskAwaitable ContinueOnCapturedContextFlow(this Task task)
  92. {
  93. return task.ConfigureAwait(true);
  94. }
  95. public static ConfiguredTaskAwaitable<T> ContinueOnCapturedContextFlow<T>(this Task<T> task)
  96. {
  97. return task.ConfigureAwait(true);
  98. }
  99. public static void Wait<TException>(this Task task)
  100. {
  101. try
  102. {
  103. task.Wait();
  104. }
  105. catch (AggregateException ex)
  106. {
  107. throw Fx.Exception.AsError<TException>(ex);
  108. }
  109. }
  110. public static bool Wait<TException>(this Task task, int millisecondsTimeout)
  111. {
  112. try
  113. {
  114. return task.Wait(millisecondsTimeout);
  115. }
  116. catch (AggregateException ex)
  117. {
  118. throw Fx.Exception.AsError<TException>(ex);
  119. }
  120. }
  121. public static bool Wait<TException>(this Task task, TimeSpan timeout)
  122. {
  123. try
  124. {
  125. if (timeout == TimeSpan.MaxValue)
  126. {
  127. return task.Wait(Timeout.Infinite);
  128. }
  129. else
  130. {
  131. return task.Wait(timeout);
  132. }
  133. }
  134. catch (AggregateException ex)
  135. {
  136. throw Fx.Exception.AsError<TException>(ex);
  137. }
  138. }
  139. public static void Wait(this Task task, TimeSpan timeout, Action<Exception, TimeSpan, string> exceptionConverter, string operationType)
  140. {
  141. bool timedOut = false;
  142. try
  143. {
  144. if (timeout > TimeoutHelper.MaxWait)
  145. {
  146. task.Wait();
  147. }
  148. else
  149. {
  150. timedOut = !task.Wait(timeout);
  151. }
  152. }
  153. catch (Exception ex)
  154. {
  155. if (Fx.IsFatal(ex) || exceptionConverter == null)
  156. {
  157. throw;
  158. }
  159. exceptionConverter(ex, timeout, operationType);
  160. }
  161. if (timedOut)
  162. {
  163. throw Fx.Exception.AsError(new TimeoutException(InternalSR.TaskTimedOutError(timeout)));
  164. }
  165. }
  166. public static Task<TBase> Upcast<TDerived, TBase>(this Task<TDerived> task) where TDerived : TBase
  167. {
  168. return (task.Status == TaskStatus.RanToCompletion) ?
  169. Task.FromResult((TBase)task.Result) :
  170. UpcastPrivate<TDerived, TBase>(task);
  171. }
  172. private static async Task<TBase> UpcastPrivate<TDerived, TBase>(this Task<TDerived> task) where TDerived : TBase
  173. {
  174. return await task.ConfigureAwait(false);
  175. }
  176. }
  177. }