栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

我将如何运行异步任务 方法同步?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我将如何运行异步任务 方法同步?

我发现这是一种变通办法,适用于所有情况(包括暂停的调度员)。这不是我的代码,我仍在努力完全理解它,但是它确实有效。

可以使用以下命令调用它:

customerList = AsyncHelpers.RunSync<List<Customer>>(() => GetCustomers());

代码来自这里

public static class AsyncHelpers{    /// <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);    }    /// <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;    }    private class ExclusiveSynchronizationContext : SynchronizationContext    {        private bool done;        public Exception InnerException { get; set; }        readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);        readonly Queue<Tuple<SendOrPostCallback, object>> items = new Queue<Tuple<SendOrPostCallback, object>>();        public override void Send(SendOrPostCallback d, object state)        { throw new NotSupportedException("We cannot send to our same thread");        }        public override void Post(SendOrPostCallback d, object state)        { lock (items) {     items.Enqueue(Tuple.Create(d, state)); } workItemsWaiting.Set();        }        public void EndMessageLoop()        { Post(_ => done = true, null);        }        public void BeginMessageLoop()        { while (!done) {     Tuple<SendOrPostCallback, object> task = null;     lock (items)     {         if (items.Count > 0)         {  task = items.Dequeue();         }     }     if (task != null)     {         task.Item1(task.Item2);         if (InnerException != null) // the method threw an exeption         {  throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);         }     }     else     {         workItemsWaiting.WaitOne();     } }        }        public override SynchronizationContext CreateCopy()        { return this;        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430441.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号