ConfigureAwait(true)不在等待的上下文中返回 [英] ConfigureAwait(true) not returning on the context it was awaited on

查看:63
本文介绍了ConfigureAwait(true)不在等待的上下文中返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样品:

 static void Main(string[] args)
 {
     int counter = 0;
     var t = new System.Timers.Timer();
     t.Interval = 3000;
     t.Elapsed += async (sender, e) =>  
     {
        Debug.WriteLine("Before await - Thread : {0} , Counter : {1}", Thread.CurrentThread.ManagedThreadId, counter);
        await Task.Delay(1000).ConfigureAwait(true);
        Debug.WriteLine("Ater await Thread : {0}, Counter : {1} ", Thread.CurrentThread.ManagedThreadId, counter);

         counter++;
         if (counter == 2)
         {
            Debug.WriteLine("Stop");
            t.Stop();
         }
     };

     t.Start();

     Console.ReadKey();
 }   

这总是输出:

 Before await - Thread : 4 , Counter : 0 
 Ater await Thread : 4, Counter : 0  
 Before await - Thread : 5 , Counter : 1 
 Ater await Thread : 4, Counter : 1  

 Stop 

为什么它没有在等待线程上返回就被调用了.它是第一次执行,但随后计时器在线程5上运行,并假定捕获异步操作何时结束的上下文,如您所见,它在线程4上返回.

Why didn't it return on the thread await was called on. it does the first time but then the timer runs on thread 5 and is suppose to capture the context for when the async operation ends, and as you can see it returns on thread 4.

推荐答案

控制台应用程序中没有任何同步上下文.

There isn't any synchronization context in console app.

如果您在WinForms中运行代码,您会发现它可以按预期工作..

If you run your code in WinForms and you'd see it would work as you expected..

这篇关于ConfigureAwait(true)不在等待的上下文中返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆