C#如何处理异步void [英] How does c# handle async void

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

问题描述

我通常对Web服务器进行编程,起初我以为必须有连续的方法链返回任务,因此将堆栈塞满可能会询问数据库是否已完成.

I generally program webservers and at first I thought that there must be continuous chain of methods that return task, so stuff up the stack may ask database if it is done.

最近我看到了wpf代码,该代码类似于:

Recently I saw wpf code, that does something like that:

    public async void Execute(object parameter)
    {
        await ExecuteAsync(parameter);
    }

在事件处理程序中调用. UI似乎是响应式的,所以我认为它确实有效.它是如何工作的?这如何转换为aspnet?

Called in event handler. UI seems to be responsive, so I guess it does work. How does it work? How does this translate to aspnet?

推荐答案

我在我的 async void的语义与async Task相同,除了例外. async void方法将在该方法的开头捕获当前的SynchronizationContext,并且该方法的任何异常都将被捕获并直接在捕获的上下文中引发.在最常见的情况下,这将导致应用程序级异常,通常是崩溃.有人称async void方法为一劳永逸",但由于其异常的行为,我更喜欢一劳永逸". :)

async void has the same semantics as async Task, except for exceptions. An async void method will capture the current SynchronizationContext at the beginning of the method, and any exceptions from that method will be captured and raised directly on that captured context. In the most common scenarios, this will cause an application-level exception, usually a crash. Some people call async void methods "fire-and-forget", but because of their exceptional behavior, I prefer "fire-and-crash". :)

避免异步无效"是一般准则,但有一个明显的例外:事件处理程序(或在逻辑上是事件处理程序的项,例如ICommand.Execute实现).

"Avoid async void" is the general guideline, with one notable exception: event handlers (or items that are logically event handlers, such as ICommand.Execute implementations).

它如何工作?这如何转换为aspnet?

How does it work? How does this translate to aspnet?

它的工作原理与其他任何async方法一样.平台的主要区别在于,当async方法完成时,UI线程不需要知道. ASP.NET需要知道这一点,因此它知道何时发送请求,但是UI不需要知道async方法何时完成.因此async void起作用.仍然最好避免,因为调用代码通常 需要知道它何时完成.

It works just like any other async method. The main platform difference is that the UI thread doesn't need to know when the async method completes. ASP.NET needs to know that so it knows when to send the request, but the UI has no need to know when the async method completes. So async void works. It's still best avoided, because the calling code usually does need to know when it completes.

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

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