public static T RunSynchronously <T>(Func <Task <T> > task) { var oldSychronizationContext = SynchronizationContext.Current; var synchronizationContext = new AsyncExtensionsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synchronizationContext); var returnedValue = default(T); synchronizationContext.Post(async _ => { try { returnedValue = await task(); } catch (Exception e) { synchronizationContext.InnerException = e; throw; } finally { synchronizationContext.EndMessageLoop(); } }, null); synchronizationContext.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldSychronizationContext); return(returnedValue); }
public static void RunSynchronously(Func <Task> task) { var oldSynchronizationContext = SynchronizationContext.Current; var synchronizationContext = new AsyncExtensionsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synchronizationContext); synchronizationContext.Post(async _ => { try { await task(); } catch (Exception e) { synchronizationContext.InnerException = e; throw; } finally { synchronizationContext.EndMessageLoop(); } }, null); synchronizationContext.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldSynchronizationContext); }