0

I am sending 'Async' emails.

I use a common 'Async' function to call the Email function as I don't need to wait for the response for the emails.

public Task SendAsync(....)
{
      ....
      return mailClient.SendMailAsync(email);
}

I need to call it from both async and sync functions.

Calling from async function

public async Task<ActionResult> AsyncFunction(...)
{
   ....
   EmailClass.SendAsync(...);
   ....
   // gives runtime error.
   // "An asynchronous module or handler completed while an asynchronous operation was still pending..."
   // Solved by using 'await EmailClass.SendAsync(...);'
}

Calling from sync function

public ActionResult syncFunction(...)
{
   ....
   EmailClass.SendAsync(...);
   ....
   // gives runtime error. 
   // "An asynchronous operation cannot be started at this time..."
   // Solved by converting the function as above function
}

Both the functions give runtime error which is then solved by using await keyword in async function.

But by using await it defeats my purpose of running it on background without waiting for response.

How do i call the async function without waiting for the response?

Ruchan
  • 3,124
  • 7
  • 36
  • 72
  • 2
    Your fundamental problem is the misunderstanding that the benefit of writing asynchronous code in this context is to fire and forget - that's not the primary intention of this kind of asyncrony, which is to free up threads while you *wait* for the tasks' completion - not to simply not bother waiting for it. – Ant P Mar 23 '15 at 13:00
  • Yep, i think i understand that now. – Ruchan Mar 23 '15 at 13:04

1 Answers1

1

You can either:

A) Create a 'Fire and Forget' request, as you are trying to do.

or

B) Await the result of your request async.

Method A will use 2 threads, the first being your request thread and the second would be the fire and forget thread. This would steal a thread from the request threadpool, causing thread starvation under heavy load.

Method B will spend 1 thread when there are things to process.. the request thread that is.

Method B will consume less resources, and while Method A potentially could be a few ms faster, but at the price of a thread(read: expensive!).

When using Async/await, the thread is only active when doing CPU work, and is freed up to serve other requests/tasks when doing IO-bound work.

While initiating a new thread, will block that thread until it is done (unless you wanna do some complicated thread synchronization).

TL;DR : Async/Await is way more efficient, and you will end up starving your webserver, if you choose to use Fire and Forget.

If you still want to run background tasks, read this blog post: Search Results How to run Background Tasks in ASP.NET - Scott Hanselman

André Snede
  • 9,899
  • 7
  • 43
  • 67