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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…