Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

c# - ConfigureAwait(true) not returning on the context it was awaited on

Sample :

 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();
 }   

this always outputs :

 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 

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There isn't any synchronization context in console app.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...