Skip to content

Instantly share code, notes, and snippets.

@tompazourek
Last active May 7, 2016 00:56
Show Gist options
  • Save tompazourek/c45a48b5e62e980c3fe70f38ad088935 to your computer and use it in GitHub Desktop.
Save tompazourek/c45a48b5e62e980c3fe70f38ad088935 to your computer and use it in GitHub Desktop.
public static class TaskExtensions
{
/// <summary>
/// Use to run async tasks in sync context. Configures await (by default set to false to not continue) and unwraps exception and result.
/// </summary>
public static TResult UnwrapResult<TResult>(this Task<TResult> task, bool continueOnCapturedContext = false)
{
try
{
task.ConfigureAwait(continueOnCapturedContext);
var result = task.Result;
return result;
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
return task.Result; // this never gets executed
}
}
/// <summary>
/// Use to run async tasks in sync context. Configures await (by default set to false to not continue) and unwraps exception.
/// </summary>
public static void UnwrapResult(this Task task, bool continueOnCapturedContext = false)
{
try
{
task.ConfigureAwait(continueOnCapturedContext);
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment