Last active
May 7, 2016 00:56
-
-
Save tompazourek/c45a48b5e62e980c3fe70f38ad088935 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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