在 ASP.NET 事件处理程序中使用 async/await 是否安全

Is it safe to use async/await in ASP.NET event handlers?(在 ASP.NET 事件处理程序中使用 async/await 是否安全?)

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

问题描述

当我遇到这个时,我正在 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();
}

在询问这个之后 问题 我对 async/await 的工作原理有了更好的理解.但后来让我震惊的是,以上述方式使用 async/await 是否安全?
我的意思是在调用 await blah 之后,调用者继续执行.这意味着它可能会在 await blah 完成之前将响应呈现回客户端.这是正确的吗?如果是这种情况,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.

推荐答案

是的,它是安全的,但并不真正推荐.推荐的方法是通过 注册AsyncTask.但是,ASP.NET(Web 窗体)将正确处理 async void 事件处理程序.

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.

当处理程序awaits 时,响应不会呈现给客户端;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 运行时如何知道 async 处理程序尚未完成感到好奇,我将在 较早的 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 事件处理程序中使用 async/await 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 ASP.NET 事件处理程序中使用 async/await 是否安全

基础教程推荐