请解释定时器事件异步/等待语法 [英] Please explain Timer event async/await syntax

查看:17
本文介绍了请解释定时器事件异步/等待语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了异步和等待语法这里这里.它确实有助于理解用法,但我在 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 事件注册与异步等待的语法:为什么可以使用 lambda 表达式中已有的 async await 关键字?

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..." );        
}

问题 2:sender & 这两个参数是什么?e 如果它们没有出现在 HandleTimer 方法中,那么好用吗?

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

推荐答案

它为 timerElapsed 事件分配一个异步 lambda.你可以这样理解异步 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.然后我们添加一个await来异步调用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()

这篇关于请解释定时器事件异步/等待语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆