Application_Error handler isn't fired when use

2019-05-18 04:51发布

I have to make an asynchronous call in Application_Error handler. So I've defined this handler with async keyword but it isn't fired on exceptions.

    protected async void Application_Error(object sender, EventArgs e)
    {
        ...

        await DoAsyncCall();

        ...
    }

The handler is fired when I remove async keyword.

BTW, I've tired to add async keyword to Application_Start handler and it works fine.

How can I make Application_Error async? Or how can I make asynchronous calls without async keyword?

2条回答
我命由我不由天
2楼-- · 2019-05-18 05:24

The solution that you posted uses Task.Run. What I think this means is that you will have one thread waiting for the async task to run and a second thread executing the task. This may mean that you end up using two threads.

I had a similar question but answered it by using the Server.TransferRequest function to initiate a new async request. I then did all the processing in the following request. By passing all the data via the header parameter of TransferRequest, I had an async error controller using only one thread. See Asynchronous error controller in ASP.NET MVC.

Hope this helps other people with this issue.

查看更多
聊天终结者
3楼-- · 2019-05-18 05:28

Finally I've found the solution:

protected void Application_Error(object sender, EventArgs e)
{
    ...

    Task task = Task.Run(async () => await DoAsyncCall());

    task.Wait();

    ...
}
查看更多
登录 后发表回答