Created
July 7, 2021 03:52
-
-
Save dj-nitehawk/43a7de03da03ae42a3bc8a44070b1ac4 to your computer and use it in GitHub Desktop.
async over sync wrapper
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 Run | |
{ | |
private static bool IsDotNetFx => | |
RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase); | |
private static readonly TaskFactory factory = | |
new TaskFactory( | |
CancellationToken.None, | |
TaskCreationOptions.None, | |
TaskContinuationOptions.None, | |
TaskScheduler.Default); | |
public static TResult Sync<TResult>(Func<Task<TResult>> func) | |
{ | |
if (IsDotNetFx) | |
{ | |
return factory.StartNew(func).Unwrap().GetAwaiter().GetResult(); | |
} | |
else | |
{ | |
return func().GetAwaiter().GetResult(); | |
} | |
} | |
public static void Sync(Func<Task> func) | |
{ | |
if (IsDotNetFx) | |
{ | |
factory.StartNew(func).Unwrap().GetAwaiter().GetResult(); | |
} | |
else | |
{ | |
func().GetAwaiter().GetResult(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment