Last active
November 16, 2018 12:08
-
-
Save jaydeepkarena/ae45e3dae9b36509acc4c185ec4ba9d5 to your computer and use it in GitHub Desktop.
C# - Run async method as sync
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 AsyncHelper | |
{ | |
private static readonly TaskFactory _taskFactory = new | |
TaskFactory(CancellationToken.None, | |
TaskCreationOptions.None, | |
TaskContinuationOptions.None, | |
TaskScheduler.Default); | |
public static TResult RunSync<TResult>(Func<Task<TResult>> func) | |
=> _taskFactory | |
.StartNew(func) | |
.Unwrap() | |
.GetAwaiter() | |
.GetResult(); | |
public static void RunSync(Func<Task> func) | |
=> _taskFactory | |
.StartNew(func) | |
.Unwrap() | |
.GetAwaiter() | |
.GetResult(); | |
} | |
Usage: | |
AsyncHelper.RunSync(() => DoAsyncStuff()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment