Created
October 8, 2016 15:18
-
-
Save develohpanda/31cd61ccdeeeb9afc460f1af86be5fad to your computer and use it in GitHub Desktop.
Run methods returning a Task synchronously, and return any output values. YOU SHOULD NEVER, EVER HAVE TO DO THIS, but if the need arises in that one rogue case....
This file contains hidden or 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 AsyncHelpers | |
{ | |
/// <summary> | |
/// Execute an async method which has a void return value synchronously | |
/// </summary> | |
/// <param name="method">Task<T/> method to execute</param> | |
public static void RunSync(Func<Task> method) | |
{ | |
Argument.CheckIfNull(method, nameof(method)); | |
Task.WaitAll(method()); | |
} | |
/// <summary> | |
/// Execute an async method which has a T return type synchronously | |
/// </summary> | |
/// <typeparam name="T">Return type</typeparam> | |
/// <param name="method">The async function to execute.</param> | |
public static T RunSync<T>(Func<Task<T>> func) | |
{ | |
Argument.CheckIfNull(func, nameof(func)); | |
T result = default(T); | |
RunSync(async () => { result = await func(); }); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment