How can I use async in Application_Error() in Global.asax.cs?

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Maybe that is not modified . Use .Result for task – or, if you want  all to finish, Task.WaitAll

jakubarnold

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Hi jakubarnold,

Thanks for your post.

What I understand from you is that you want to write mvc application exception message to remote server asynchronously.

For this issue, you should mark the Application_Error as async like below:

protected async void Application_Error(object sender, EventArgs e) 
        {
            Exception ex = Server.GetLastError();
            var isSuccess=await MethodAsync(ex);
        
        }
async Task<bool> MethodAsync(Exception ex)
        {
            //your code write exception to remote server.
            //...............

            return true;
        }

Thanks.

Best Regards!

The HTTP pipeline has APIs to register for async versions of all the methods you see in global.asax. You can then incorporate that with Tasks. This might help:

http://brockallen.com/2013/07/27/implementing-async-http-modules-in-asp-net-using-tpls-task-api/

Is your intention is to return the page back to the user while logging the error? Typically this makes sense as you don’t want to block user while logging errors. Async does not support this behavior. It will still be a synchronous call to your user. Please
check the below blog for more details

Async Doesn’t Change the HTTP Protocol

If your intension is not to hold up the web server thread while doing the error logging, I recommend using async HttpModules for this.

Implementing async HTTP modules in ASP.NET using TPL’s Task API

Leave a Reply