在ASP.NET事件处理程序是否安全使用异步/等待? [英] Is it safe to use async/await in ASP.NET event handlers?

查看:171
本文介绍了在ASP.NET事件处理程序是否安全使用异步/等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做ASP.NET中的一些编码,当我碰到这个就来了:

I was doing some coding in ASP.NET when I came across this:

protected async void someButtonClickHandler(...)
{
    if(await blah)
        doSomething();
    else
        doSomethingElse();
}

询问后,<一个href=\"http://stackoverflow.com/questions/27278713/why-should-a-void-method-be-async-to-be-able-to-await\">this问题我有异步 / 更好地了解如何的等待的作品。但后来我突然想到是可以安全使用异步 / 等待在上面显示的方式?结果
我的意思是叫的await等等等待等等完成。这是正确的吗?如果这是发生了什么的情况下 DoSomething的() / doSomethingElse()。他们才会被执行?如果他们不执行用户看到自己的变化的影响?结果
在我的情况下,这些方法来改变显示给用户的一些数据,但我也想知道在一般情况下会发生什么。

After asking this question I got a better understanding of how async/await works. But then it struck me is it safe to use async/await in the manner shown above?
I mean after calling await blah the caller continues execution. Which means it might render the response back to client before await blah completes. Is this right? And if this is the case what happens to doSomething()/doSomethingElse(). Will they ever be executed? If they're executed does the user see the effects of their changes?
In my case these methods change some data displayed to the user, but I'd also like to know what would happen in the general case.

推荐答案

是的,它是安全的,但并不推荐使用。在<一个href=\"http://www.asp.net/web-forms/overview/performance-and-caching/using-asynchronous-methods-in-aspnet-45\">recommended这样做,这是通过 RegisterAsyncTask 。但是,ASP.NET(Web窗体)将正确处理异步无效事件处理程序。

Yes it is safe, but not really recommended. The recommended way to do this is via RegisterAsyncTask. However, ASP.NET (Web Forms) will correctly handle async void event handlers.

响应不渲染当处理程序等待 S上的客户端;在的await 只产生于ASP.NET运行时,而不是客户端。 ASP.NET运行时了解到,事件处理程序还没有完成,因此它知道没有发送响应。当事件处理程序完成,ASP.NET运行时通过发送当时的响应来响应。

The response is not rendered to the client when the handler awaits; the await only yields to the ASP.NET runtime, not to the client. The ASP.NET runtime is aware that the event handler has not completed, so it knows not to send the response. When the event handler completes, the ASP.NET runtime responds by sending the response at that time.

我对异步ASP.NET 的 MSDN文章,你会发现有帮助。如果您想了解ASP.NET运行时是怎么知道的异步的处理程序还没有完成,我盖在的an前面MSDN文章

I have an MSDN article on async ASP.NET that you may find helpful. If you're curious about how the ASP.NET runtime is aware that the async handler has not completed, I cover that in an earlier MSDN article.

这篇关于在ASP.NET事件处理程序是否安全使用异步/等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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