Skip to content

Instantly share code, notes, and snippets.

@develohpanda
Created October 8, 2016 15:18
Show Gist options
  • Save develohpanda/31cd61ccdeeeb9afc460f1af86be5fad to your computer and use it in GitHub Desktop.
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....
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