コード例 #1
0
ファイル: AsyncHelpers.cs プロジェクト: yi-liu9/aws-sdk-net
        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);
            }
        }
コード例 #2
0
        /// <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);
            }
        }
コード例 #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>(Task <T> task)
        {
            var oldContext = SynchronizationContext.Current;
            var synch      = new ExclusiveSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(synch);
            T rs = default(T);

            synch.Post(async _ =>
            {
                try
                {
                    rs = await task.ConfigureAwait(false);
                }
                catch (System.Exception e)
                {
                    synch.InnerException = e;
                    throw;
                }
                finally
                {
                    synch.EndMessageLoop();
                }
            }, null);
            synch.BeginMessageLoop();
            SynchronizationContext.SetSynchronizationContext(oldContext);
            return(rs);
        }
コード例 #4
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);
        }
コード例 #5
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 Logger.Fatal <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);
        }
コード例 #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 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);
        }
コード例 #7
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);
        }
コード例 #8
0
ファイル: AsyncUtil.cs プロジェクト: lulzzz/vita
        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);
        }
コード例 #9
0
        /// <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);
            }
        }
コード例 #10
0
        /// <summary>
        /// Executes synchronously an async <see cref="Task{T}"/> method which has a <typeparamref name="T"/> return type
        /// </summary>
        /// <typeparam name="T">Return Type</typeparam>
        /// <param name="task"><see cref="Task{T}"/> method to execute</param>
        /// <returns>Return value ot the task</returns>
        /// <exception cref="ArgumentNullException"><paramref name="task"/> is null</exception>
        public static T RunSync <T>(Func <Task <T> > task)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            var oldContext = SynchronizationContext.Current;
            var synch      = new ExclusiveSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(synch);
            var ret = default(T);

            synch.Post(async _ =>
            {
                try
                {
                    ret = await task().ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    synch.InnerException = e;
                    throw;
                }
                finally
                {
                    synch.EndMessageLoop();
                }
            }, null);
            synch.BeginMessageLoop();
            SynchronizationContext.SetSynchronizationContext(oldContext);
            return(ret);
        }
コード例 #11
0
ファイル: AsyncHelper.cs プロジェクト: radtek/DataAccess
 /// <summary>
 /// Constructs the AsyncBridge by capturing the current
 /// SynchronizationContext and replacing it with a new
 /// ExclusiveSynchronizationContext.
 /// </summary>
 internal AsyncBridge()
 {
     _oldContext     = SynchronizationContext.Current;
     _currentContext =
         new ExclusiveSynchronizationContext(_oldContext);
     SynchronizationContext
     .SetSynchronizationContext(_currentContext);
 }
コード例 #12
0
        public static T RunSync <T>(this Func <Task <T> > task)
        {
            var oldContext = SynchronizationContext.Current;
            var synch      = new ExclusiveSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(synch);

            T ret = default !;
コード例 #13
0
 /// <summary>
 /// Constructs the AsyncBridge by capturing the current
 /// SynchronizationContext and replacing it with a new
 /// ExclusiveSynchronizationContext.
 /// </summary>
 internal AsyncBridge()
 {
     OldContext     = SynchronizationContext.Current;
     CurrentContext =
         new ExclusiveSynchronizationContext(OldContext);
     SynchronizationContext
     .SetSynchronizationContext(CurrentContext);
 }
コード例 #14
0
    public void AwaitableSyncContexts()
    {
        var r = new ExclusiveSynchronizationContext();

        Task.Factory.StartNew(async() => {
            SynchronizationContext.Current.AssertDoesNotEqual(r);
            await r;
            SynchronizationContext.Current.AssertEquals(r);
        }).Unwrap().AssertRanToCompletion();
    }
コード例 #15
0
        public static void RunSync(Func <Task> task)
        {
            ExclusiveSynchronizationContext synch = new ExclusiveSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(synch);
            synch.Post(delegate(object _) {
                < > c__DisplayClass0_0.<< RunSync > b__0 > d local;
                local.< > 4__this    = (< > c__DisplayClass0_0) this;
                local.< > t__builder = AsyncVoidMethodBuilder.Create();
                local.< > 1__state   = -1;
                local.< > t__builder.Start << > c__DisplayClass0_0.<< RunSync > b__0 > d > (ref local);
            }, null);
コード例 #16
0
            public ExclusiveSynchronizationContext(SynchronizationContext old)
            {
                ExclusiveSynchronizationContext oldEx =
                    old as ExclusiveSynchronizationContext;

                if (null != oldEx)
                {
                    this._items = oldEx._items;
                }
                else
                {
                    this._items = new EventQueue();
                }
            }
    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();
    }
コード例 #18
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);
        }
コード例 #19
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);
        }
    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);
    }
コード例 #21
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));
        }
コード例 #22
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);
        }
コード例 #23
0
ファイル: AsyncHelper.cs プロジェクト: tomasdeml/AkkaCQRS
        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);
        }
コード例 #24
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);
        }
コード例 #25
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);
            }
        }
コード例 #26
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);
        }
コード例 #27
0
ファイル: AsyncHelper.cs プロジェクト: tomasdeml/AkkaCQRS
        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);
        }
コード例 #28
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);
        }
コード例 #29
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);
            }
        }
コード例 #30
0
 public SyncRunnerScope()
 {
     _oldContext     = SynchronizationContext.Current;
     _currentContext = new ExclusiveSynchronizationContext(_oldContext);
     SynchronizationContext.SetSynchronizationContext(_currentContext);
 }
コード例 #31
0
 private AsyncRunner()
 {
     OldContext     = SynchronizationContext.Current;
     CurrentContext = new ExclusiveSynchronizationContext(OldContext);
     SynchronizationContext.SetSynchronizationContext(CurrentContext);
 }