Last active
September 19, 2018 07:07
-
-
Save DamienBraillard/e9666d547ac405be342d04822f1b4c7c to your computer and use it in GitHub Desktop.
Run async method as sync
This file contains hidden or 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
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