Is it safe to use async/await in ASP.NET event handlers?

前端 未结 1 1477
名媛妹妹
名媛妹妹 2020-12-18 22:22

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

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


        
相关标签:
1条回答
  • 2020-12-18 23:13

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题