Skip to content

Commit

Permalink
add PropagateExceptions() and PropagateExceptionsTo()
Browse files Browse the repository at this point in the history
  • Loading branch information
tibel committed Apr 2, 2015
1 parent 4338b6c commit c052d1a
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Weakly/Tasks/TaskHelper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -164,6 +165,36 @@ public static Task<T> ObserveException<T>(this Task<T> task)
return (Task<T>)((Task)task).ObserveException();
}

/// <summary>
/// Propagates any exceptions that occurred on the specified task.
/// </summary>
/// <param name="task">The Task whose exceptions are to be propagated.</param>
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();
}

/// <summary>
/// Propagates any exceptions that occurred on the specified task to the specified synchronization context.
/// </summary>
/// <param name="task">The Task whose exceptions are to be propagated.</param>
/// <param name="synchronizationContext">The SynchronizationContext that should get the exception.</param>
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

/// <summary>
Expand Down

0 comments on commit c052d1a

Please sign in to comment.