Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created Jul 7, 2021
Embed
What would you like to do?
async over sync wrapper
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