Ejemplo n.º 1
0
        /// <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);
        }
Ejemplo n.º 2
0
        /// <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);
        }
Ejemplo n.º 3
0
        /// <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);
        }
Ejemplo n.º 4
0
        /// <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);
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        /// <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 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);
            }
        }
    public void NoOverlap()
    {
        var r = new ExclusiveSynchronizationContext();
        var n = 0;

        for (var i = 0; i < 1000; i++)
        {
            r.Post(z => {
                Assert.IsTrue(Interlocked.Increment(ref n) == 1);
                Assert.IsTrue(Interlocked.Decrement(ref n) == 0);
            }, null);
        }
        var a = new TaskCompletionSource();

        r.Post(z => a.SetRanToCompletion(), null);
        a.Task.AssertRanToCompletion();
    }
    public void NoInterference()
    {
        var r = new ExclusiveSynchronizationContext();
        var n = 0;
        var t = Task.WhenAll(Enumerable.Range(0, 5).Select(async e => await Task.Factory.StartNew(() => {
            for (var i = 0; i < 500; i++)
            {
                r.Post(z => {
                    n += 1;
                }, null);
            }
            var a = new TaskCompletionSource();
            r.Post(z => a.SetRanToCompletion(), null);
            a.Task.AssertRanToCompletion();
        })));

        t.AssertRanToCompletion(timeout: TimeSpan.FromSeconds(20)); // lots of work, long timeout
        Assert.IsTrue(n == 500 * 5);
    }
Ejemplo n.º 9
0
                /// <summary>
                /// Execute's an async task with a void return type
                /// from a synchronous context
                /// </summary>
                /// <param name="task">Task to execute</param>
                /// <param name="callback">Optional callback</param>
                public void Run(Task task, Action <Task> callback = null)
                {
                    CurrentContext.Post(async _ =>
                    {
                        try
                        {
                            Increment();
                            await task;

                            callback?.Invoke(task);
                        }
                        catch (Exception e)
                        {
                            CurrentContext.InnerException = e;
                        }
                        finally
                        {
                            Decrement();
                        }
                    }, null);//new object()
                }
Ejemplo n.º 10
0
            /// <summary>
            /// Execute's an async task with a void return type
            /// from a synchronous context
            /// </summary>
            /// <param name="task">Task to execute</param>
            /// <param name="callback">Optional callback</param>
            public void Run(Task task, Action <Task> callback = null)
            {
                CurrentContext.Post(async _ =>
                {
                    try
                    {
                        Increment();
                        await task;

                        if (null != callback)
                        {
                            callback(task);
                        }
                    }
                    catch (Exception e)
                    {
                        CurrentContext.InnerException = e;
                    }
                    finally
                    {
                        Decrement();
                    }
                }, null);
            }
Ejemplo n.º 11
0
 /// <summary>
 /// Execute's an async task with a void return type
 /// from a synchronous context
 /// </summary>
 /// <param name="task">Task to execute</param>
 /// <param name="callback">Optional callback</param>
 public void Run(Task task, Action <Task> callback = null)
 {
     _hasAsyncTasks = true;
     _currentContext.Post(
         async _ => {
         try {
             Increment();
             await task.ConfigureAwait(true);
             callback?.Invoke(task);
         } catch (Exception e) {
             _currentContext.InnerException = e;
         } finally {
             Decrement();
         }
     },
         null);
 }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
        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));
        }
Ejemplo n.º 15
0
        /// <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);
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
        /// <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);
        }
Ejemplo n.º 18
0
            /// <summary>
            /// Execute's an async task with a void return type
            /// from a synchronous context
            /// </summary>
            /// <param name="task">Task to execute</param>
            /// <param name="callback">Optional callback</param>
            public void Run(Task task, Action <Task> callback = null)
            {
                _currentContext.Post(async _ =>
                {
                    try
                    {
                        Increment();
                        await task;

                        callback?.Invoke(task);
                    }
                    catch (Exception e)
                    {
                        _currentContext.InnerException = ExceptionDispatchInfo.Capture(e);
                    }
                    finally
                    {
                        Decrement();
                    }
                }, null);
            }
Ejemplo n.º 19
0
        /// <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);
            }
        }
Ejemplo n.º 20
0
        /// <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);
        }
Ejemplo n.º 21
0
            /// <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();
            }
Ejemplo n.º 22
0
        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);
        }
Ejemplo n.º 23
0
        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);
        }
Ejemplo n.º 24
0
        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);
            }
        }