如何在C#中调用异步void事件处理程序? [英] How are async void event handlers called in C#?

查看:363
本文介绍了如何在C#中调用异步void事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将事件处理程序声明为async void,那么.NET框架将它们同步还是异步调用?

If I declare my event handlers as async void, will they be called synchronously or asynchronously by the .NET framework?

即,给出以下代码:

async void myButton_click(object sender, EventArgs e) {
   do stuff
   await longRunning()
   do more stuff
}

我可以确定将在GUI线程上执行操作"行吗?

Can I be sure that the "do stuff" line will be executed on the GUI thread?

推荐答案

事件处理程序将被同步调用,并且不会等到事件处理程序完成后才等待,而是等待事件处理程序返回.

Event handlers will be called synchronously and doesn't wait(await) till the event handler completes, but waits till the event handler returns.

如果前面的句子很混乱,我会尽力将其解释清楚.当所有等待点均已执行且方法主体的末尾已到达或执行了任何return语句时,异步方法完成(忽略异常).但是,异步方法会在您尚未完成的Task的第一个await语句中返回.换句话说,异步方法可以返回多次,但只能完成一次.

If previous sentence was confusing enough, I'll try to explain it clear. Asynchronous methods completes when all the await points are executed and the end of the method body has reached or any return statement is executed(Ignoring the exception). But asynchronous method returns as soon as you hit the first await statement for the Task which is not yet completed. In other words asynchronous method can return several times but can complete only once.

所以现在我们知道异步方法何时完成并返回.事件处理程序将假定您的方法在实际完成时返回,而不是在返回时立即完成.

So now we know when does a asynchronous method completes and returns. Event handler will assume your method has completed as soon as it returns not when it actually completes.

事件处理程序到达第一个await语句后,它将立即返回,如果同一事件处理程序附加了更多方法,它将继续执行它们而不会等待异步方法执行完成.

As soon as your event handler reaches first await statement, it will return, if there are more methods attached to same event handler, it will continue executing them without waiting for the asynchronous method to complete.

是的,如果UI线程触发了事件,则会在UI线程中执行do stuff,并且只要不调用longRunning().ConfigureAwait(false),就会在UI线程中执行do more stuff.

Yes, do stuff will be executed in UI thread if the UI thread fires the event and yes do more stuff will also be executed in UI thread as long as longRunning().ConfigureAwait(false) isn't called.

这篇关于如何在C#中调用异步void事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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