Is it safe to use async/await in ASP.NET event handlers?
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 await
s; 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.