请说明Timer事件异步/等待语法 [英] Please explain Timer event async/await syntax
问题描述
我研究了异步并等待语法此处和here 。它真的有助于了解使用情况,但我发现一个有趣的语法示例在 MSDN ,我只是不明白。
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.
问题:
可以有人请向我解释这个 System.Timers.Timer
事件注册与asynch等待的语法:
为什么可以使用 async
await
已经在lambda表达式中的关键字
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..." );
}
问题2:
什么是两个参数发件人
& e
如果它们没有出现在 HandleTimer
方法中,那么很好?
Question 2:
And what are the two parameters sender
& e
good for if they don't appear in the HandleTimer
method?
推荐答案
它为$ code> timer $ c $的 Elapsed
事件分配一个async lambda C>。你可以这样理解async lambda:首先,以下是lambda:
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()
此lambda同时调用 HandleTimer
。然后我们添加一个等待以异步方式调用 HandleTimer
this lambda calls HandleTimer
synchronously. Then we add an await to call HandleTimer
asynchronously:
(sender, e) => await HandleTimer()
但这不会工作,因为要异步调用异步你必须是异步的,因此 async
关键字:
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()
这篇关于请说明Timer事件异步/等待语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!