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
449 views
in Technique[技术] by (71.8m points)

c# - Please explain Timer event async/await syntax

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("
Handler not implemented..." );        
}

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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

...