Please explain Timer event async/await syntax

£可爱£侵袭症+ 提交于 2019-12-29 07:54:07

问题


I researched the asynch and await syntax here and here. It really helps to understand the usage but I found an intriguing syntax example on MSDN which I just don't understand.

Question: Could someone please explain to me the syntax of this System.Timers.Timer event registration with asynch await: Why can you use the async await keywords already in the lambda expression?

Timer timer = new Timer(1000);
timer.Elapsed += async ( sender, e ) => await HandleTimer();

private Task HandleTimer()
{
    Console.WriteLine("\nHandler not implemented..." );        
}

Question 2: And what are the two parameters sender & e good for if they don't appear in the HandleTimer method?


回答1:


It assigns an async lambda to the Elapsed event of timer. You can understand the async lambda this way: first, the following is a lambda:

(sender, e) => HandleTimer()

this lambda calls HandleTimer synchronously. Then we add an await to call HandleTimer asynchronously:

(sender, e) => await HandleTimer()

but this won't work because to call something asynchronously you have to be asynchronous yourself, hence the async keyword:

async (sender, e) => await HandleTimer()



回答2:


This is just an asynchronous lambda expression. It's equivalent to:

timer.Elapsed = CallHandleTimer;

async void CallHandleTimer(object sender, EventArgs e)
{
    await HandleTimer();
}



回答3:


The code you've given is an anonymous function written as a lambda expression.

So what's really happening is that for the timer elapsed event you're assigning the EventHandler as async ( sender, e ) => await HandleTimer();.

which translates to something like

timer.Elapsed += AnonFunc;

async void AnonFunc(object sender, EventArgs e)
{
    await HandleTImer();
}

It seems that it's the lambda that's tripping you up.



来源:https://stackoverflow.com/questions/37679480/please-explain-timer-event-async-await-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!