Created
November 13, 2020 17:30
-
-
Save aaronhoffman/269962510591a1f6fc84e9c8f5f2de32 to your computer and use it in GitHub Desktop.
Run Async Methods Synchronously
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) | |
{ | |
if (func == null) | |
{ | |
return default(TResult); | |
} | |
var task = func(); | |
if (task == null) | |
{ | |
return default(TResult); | |
} | |
return _taskFactory | |
.StartNew(() => task) | |
.Unwrap() | |
.GetAwaiter() | |
.GetResult(); | |
} | |
public static void RunSync(Func<Task> func) | |
{ | |
if (func == null) | |
{ | |
return; | |
} | |
var task = func(); | |
if (task == null) | |
{ | |
return; | |
} | |
_taskFactory | |
.StartNew(() => task) | |
.Unwrap() | |
.GetAwaiter() | |
.GetResult(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment