Created
January 24, 2013 16:30
-
-
Save sandcastle/4624488 to your computer and use it in GitHub Desktop.
Async helper methods for ensure exceptions are raised and unwrapped if possible.
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
/// <summary> | |
/// Helper methods for ensure exceptions are raised and unwrapped if possible. | |
/// </summary> | |
public static class AsyncHelpers | |
{ | |
/// <summary> | |
/// Returns the result of the task, if a single exception is found it unwraps, otherwise throws the aggregate. | |
/// </summary> | |
/// <typeparam name="T">The type of the result the task returns.</typeparam> | |
/// <param name="task">The task.</param> | |
/// <returns>The result of the task.</returns> | |
public static T Return<T>(this Task<T> task) | |
{ | |
try | |
{ | |
return task.Result; | |
} | |
catch (AggregateException exception) | |
{ | |
// Unwrap if only one exception caught | |
if (exception.InnerExceptions.Count == 1) | |
{ | |
throw exception.InnerException; | |
} | |
throw; | |
} | |
} | |
/// <summary> | |
/// Waits for the task to complete, if a single exception is found it unwraps, otherwise throws the aggregate. | |
/// </summary> | |
/// <param name="task">The task.</param> | |
public static void Return(this Task task) | |
{ | |
try | |
{ | |
task.Wait(); | |
} | |
catch (AggregateException exception) | |
{ | |
// Unwrap if only one exception caught | |
if (exception.InnerExceptions.Count == 1) | |
{ | |
throw exception.InnerException; | |
} | |
throw; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment