diff --git a/src/Weakly/Tasks/TaskHelper.cs b/src/Weakly/Tasks/TaskHelper.cs index 8cf5350..826b109 100644 --- a/src/Weakly/Tasks/TaskHelper.cs +++ b/src/Weakly/Tasks/TaskHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; @@ -164,6 +165,36 @@ public static Task ObserveException(this Task task) return (Task)((Task)task).ObserveException(); } + /// + /// Propagates any exceptions that occurred on the specified task. + /// + /// The Task whose exceptions are to be propagated. + public static void PropagateExceptions(this Task task) + { + if (!task.IsCompleted) + throw new InvalidOperationException("The task has not completed."); + + if (task.IsFaulted) + ExceptionDispatchInfo.Capture(task.Exception.InnerException).Throw(); + } + + /// + /// Propagates any exceptions that occurred on the specified task to the specified synchronization context. + /// + /// The Task whose exceptions are to be propagated. + /// The SynchronizationContext that should get the exception. + public static void PropagateExceptionsTo(this Task task, SynchronizationContext synchronizationContext) + { + if (!task.IsCompleted) + throw new InvalidOperationException("The task has not completed."); + + if (task.IsFaulted) + { + var exceptionInfo = ExceptionDispatchInfo.Capture(task.Exception.InnerException); + synchronizationContext.Post(state => ((ExceptionDispatchInfo)state).Throw(), exceptionInfo); + } + } + #endregion ///