Skip to content

Instantly share code, notes, and snippets.

@DamienBraillard
Last active September 19, 2018 07:07
Show Gist options
  • Save DamienBraillard/e9666d547ac405be342d04822f1b4c7c to your computer and use it in GitHub Desktop.
Save DamienBraillard/e9666d547ac405be342d04822f1b4c7c to your computer and use it in GitHub Desktop.
Run async method as sync
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace MvvmFramework
{
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)
{
return TaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func<Task> func)
{
TaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
public static void RunSyncWithDispatcher(Func<Task> func)
{
DispatcherFrame frame = new DispatcherFrame();
TaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.OnCompleted(() => frame.Continue = false);
Dispatcher.PushFrame(frame);
}
public static TResult RunSyncWithDispatcher<TResult>(Func<Task<TResult>> func)
{
DispatcherFrame frame = new DispatcherFrame();
var awaiter = TaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter();
awaiter.OnCompleted(() => frame.Continue = false);
Dispatcher.PushFrame(frame);
return awaiter.GetResult();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment