Bagzli Bagzli - 3 months ago 21
C# Question

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
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.

usr usr

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?!