public static T RunSync <T>(Func <Task <T> > task, Action <Exception> onError = null) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { ret = await task().ConfigureAwait(false); } catch (Exception e) { synch.InnerException = e; onError?.Invoke(e); } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ret); }
/// <summary> /// Execute's an async Task<T> method which has a T return type synchronously /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="task">Task<T> method to execute</param> /// <returns></returns> public static T RunSync <T>(Func <Task <T> > task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { ret = await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ret); }
/// <summary> /// Executes synchronously an async <see cref="Task"/> method which has a void return value /// </summary> /// <param name="task"><see cref="Task"/> method to execute</param> /// <exception cref="ArgumentNullException"><paramref name="task"/> is null</exception> public static void RunSync(Func <Task> task) { if (task == null) { throw new ArgumentNullException(nameof(task)); } var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task().ConfigureAwait(false); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); }
/// <summary> /// Execute's an async Task<T> method which has a void return value synchronously /// </summary> /// <param name="task">Task<T> method to execute</param> public static void RunSync(Func <Task> task) { SynchronizationContext oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); }
/// <summary> /// Execute's an async <see cref="Task{TResult}"/> method which has a T return type synchronously /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="task"><see cref="Task{TResult}"/> method to execute</param> /// <returns></returns> public static T RunSync <T>(Func <Task <T> > task) { var synch = new ExclusiveSynchronizationContext(); using (new SetSynchronizationContext(synch)) { T ret = default(T); synch.Post(async _ => { try { ret = await task(); } catch (Exception e) { synch.InnerExceptionDispatchInfo = ExceptionDispatchInfo.Capture(e); throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); return(ret); } }
/// <summary> /// Execute's an async Task<T> method which has a void return value synchronously /// </summary> /// <param name="task">Task<T> method to execute</param> public static void RunSync(Func<Task> task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); }
public static T RunSync <T>(Func <Task <T> > workItem) { var prevContext = SynchronizationContext.Current; try { var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { ret = await workItem(); } catch (Exception e) { synch.ObjectException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); return(ret); } finally { SynchronizationContext.SetSynchronizationContext(prevContext); } }
/// <summary> /// Execute's an async Task method which has a T return type synchronously /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="task">Task method to execute</param> /// <returns></returns> public static T RunSync <T>(Func <Task <T> > task) { var oldContext = SynchronizationContext.Current; using (var synch = new ExclusiveSynchronizationContext()) { SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(_ => { try { ret = task().ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ret); } }
// ******************************************************************************************************************************* #region - Tasks - /// <summary> /// Execute's an async Task<T> method which has a void return value synchronously /// </summary> public static void RunSync(Task task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task.ConfigureAwait(false); } catch (System.Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); }
/// <summary> /// Disposes the object /// </summary> public void Dispose() { try { _currentContext.BeginMessageLoop(); } finally { SynchronizationContext.SetSynchronizationContext(_oldContext); } }
/// <summary> /// Disposes the object /// </summary> public void Dispose() { try { CurrentContext.BeginMessageLoop(); } catch (Exception e) { throw e; } finally { SynchronizationContext .SetSynchronizationContext(OldContext); } }
public static T RunSync <T>(Func <Task <T> > task) { var result = default(T); Stopwatch sp = Stopwatch.StartNew(); var oldContext = SynchronizationContext.Current; try { var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { result = await task().ConfigureAwait(false); } catch (Exception e) { synch.InnerException = e; throw; } finally { sp.Stop(); synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); } catch (AggregateException ex) { var exception = ex.ExtractSingleInnerException(); if (exception is OperationCanceledException) { throw new TimeoutException("Operation timed out after: " + sp.Elapsed, ex); } ExceptionDispatchInfo.Capture(exception).Throw(); } finally { SynchronizationContext.SetSynchronizationContext(oldContext); } return(result); }
public static T RunSync <T>(Func <Task <T> > task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { ret = await task(); } catch (Exception e) { try { var exc = ((IoTConnect.Model.IoTConnectException)e); if (exc != null && exc.error != null) { synch.InnerException = new Exception(exc.error.FirstOrDefault().Message); } else { synch.InnerException = new Exception(e.InnerException.Message); } throw; } catch (Exception ex) { synch.InnerException = new Exception(e.Message); throw; } } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ret); }
/// <summary> /// GetSpecialtyByID -> Sincrono /// Usado para ir buscar a especialidade no caso do utilizador selecionar primeiro o ato médico /// </summary> /// <param name="task"></param> /// <returns>Returna uma especialidade</returns> public static ServiceReturn <Specialty> RunSync(Func <Task <ServiceReturn <Specialty> > > task) { #region uimessage var uiMessages = new Dictionary <string, string>(); if (!string.IsNullOrEmpty("")) { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, ""); } else { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, "Erro ao obter a especialidade"); } if (!string.IsNullOrEmpty("")) { uiMessages.Add(ServiceReturnHandling.SuccessMessageKey, ""); } #endregion var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); ServiceReturn <Specialty> ret = default(ServiceReturn <Specialty>); synch.Post(async _ => { try { ret = await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ret);//ServiceReturnHandling.BuildSuccessCallReturn<Specialty>(ret, uiMessages); }
public static ServiceReturn <List <ScheduledAppointment> > RunSync(Func <Task <List <ScheduledAppointment> > > task) { #region uimessage var uiMessages = new Dictionary <string, string>(); if (!string.IsNullOrEmpty("")) { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, ""); } else { uiMessages.Add(ServiceReturnHandling.GenericMessageKey, "Erro ao concluir a marcação"); } if (!string.IsNullOrEmpty("")) { uiMessages.Add(ServiceReturnHandling.SuccessMessageKey, ""); } #endregion var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); List <ScheduledAppointment> ret = default(List <ScheduledAppointment>); synch.Post(async _ => { try { ret = await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ServiceReturnHandling.BuildSuccessCallReturn <List <ScheduledAppointment> >(ret, uiMessages)); }
public static void Run(Func <Task> item) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await item(); } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); }
/// <summary> /// Execute's an async Task<T> method which has a T return type synchronously /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="task">Task<T> method to execute</param> /// <returns></returns> public static T RunSync <T>(Func <Task <T> > task, int timeout) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { if (timeout == 0) { ret = await task(); } else { var t = task(); var res = await Task.WhenAny(t, Task.Delay(timeout)); if (res != t) { throw new TaskCanceledException(); } ret = t.Result; } } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ret); }
/// <summary> /// Выполняет задачу синхронно /// </summary> /// <typeparam name="T">Тип объекта, который возвращает задача</typeparam> /// <param name="task">задача</param> /// <returns>Объект, который вернула задача</returns> public static T RunSync <T>([NotNull] Func <Task <T> > task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); try { SynchronizationContext.SetSynchronizationContext(synch); var ret = default(T); synch.Post(async _ => { try { var running = task(); if (running == null) { throw new NullReferenceException("task"); } ret = await running; } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); return(ret); } finally { SynchronizationContext.SetSynchronizationContext(oldContext); } }
/// <summary> /// 同步调用异步方法并避免死锁,https://github.com/tejacques/AsyncBridge /// </summary> /// <typeparam name="T"></typeparam> /// <param name="task"></param> /// <returns></returns> public static T RunSync <T>(this Func <Task <T> > task) { var oldContext = SynchronizationContext.Current; var currentContext = new ExclusiveSynchronizationContext(oldContext); SynchronizationContext.SetSynchronizationContext(currentContext); T result = default(T); try { currentContext.Post(async _ => { try { result = await task(); } catch (Exception e) { currentContext.InnerException = e; } finally { currentContext.EndMessageLoop(); } }, null); currentContext.BeginMessageLoop(); } catch (AggregateException e) { throw e?.InnerException ?? e; } finally { SynchronizationContext.SetSynchronizationContext(oldContext); } return(result); }
public static T Run <T>(Func <Task <T> > item) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { ret = await item(); } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return(ret); }
/// <summary> /// Executes an async Task method which has a void return value synchronously /// </summary> /// <param name="task">Task execute</param> public void RunSync(Task task, Action <Task> continuation = null) { _currentContext.Post(async _ => { try { Increment(); await task; continuation?.Invoke(task); } catch (Exception e) { _currentContext.InnerException = e; } finally { Decrement(); } }, null); _currentContext.BeginMessageLoop(); }
public static void RunSync(Func <Task> task) { logger.DebugLog("Start AsyncHelpers"); var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task(); } catch (Exception e) { var exc = ((IoTConnect.Model.IoTConnectException)e); if (exc != null && exc.error != null) { synch.InnerException = new Exception(exc.error.FirstOrDefault().Message); } else { synch.InnerException = new Exception(e.InnerException.Message); } throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); }
public static void RunSync(Func <Task> task) { var oldContext = SynchronizationContext.Current; try { var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task().ConfigureAwait(false); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); } catch (AggregateException ex) { var exception = ex.ExtractSingleInnerException(); ExceptionDispatchInfo.Capture(exception).Throw(); } finally { SynchronizationContext.SetSynchronizationContext(oldContext); } }