Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous call from Application_Error()

I am trying to figure out how to create an asynchronous call from Application_Error Method in MVC.

I have an e-mail dll that I have written which sends out an e-mail via asynchronous call using Smtp Client.

The problem is that when I call SendEmail method in my dll I have conflict of needing to await for the call. Now if I try something like this:

protected async void Application_Error()
{
    var await emailService.SendEmail("Hello World");
}

It will not work, the method will never even be called.

Is there a way for me to make an asynchronous call from a synchronous method? My research online hinted at HttpServerUtility.TransferRequest possibly being the answer but I could not figure out how to make it work with my request, it just doesn't make sense to me at the moment.

like image 797
Bagzli Avatar asked Jan 27 '16 13:01

Bagzli


2 Answers

For those that may encounter this issue in the future, here is another solution that may be a bit more robust. Instead of using ThreadPool.QueueUserWorkItem() you can use HostingEnvironment.QueueBackgroundWorkItem(). Doing things this way, asks the server to make a bit more of an effort to complete these tasks before shutting down.

Here's an example from a recent project:

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    HostingEnvironment.QueueBackgroundWorkItem(ct =>
        ExceptionLogger.LogAsync(ex));
}
like image 141
Matt Avatar answered Nov 11 '22 08:11

Matt


limitation of the dll, i cannot change it.

I don't know why that async call does not send an email. It should. There's a bug somewhere.

But a workaround is:

Task.Run(async () => { await emailService.SendEmail("Hello World"); }).Wait();

You could simplify and optimize this but this is the simplest way to bring the idea across. This pattern is always a safe way to synchronously call an async method. Not good for perf, but does not matter here because sending an email is 1000x more expensive than the overhead.

If you want to keep the async behavior you could remove the Wait. Although at that point I wonder why sending is not working in the first place. Is the bug triggered by the async behavior or is it always there?!

like image 37
usr Avatar answered Nov 11 '22 09:11

usr