williamsandonz
williamsandonz

Reputation: 16460

WebApi how to send asyncronous email after returning response to user?

Emails are taking too long to send (sometimes up to 7-8) seconds.

I want to send a response back to my clients without them having to wait for the email to send. Is this possible?

public async Task<IHttpActionResult> Action()
{
  //Do something
  await email.sendAsync(); //Can take up to 10 seconds...
  return Ok();
}

I can remove the await, but I obviously get a An asynchronous module or handler completed while an asynchronous operation was still pending

How can I achieve this?

Upvotes: 0

Views: 686

Answers (1)

JohanP
JohanP

Reputation: 5472

Ideally you would want to offload this work onto some other process, maybe a queue and then have some subscribers process off that queue to send the email but that is a lot of work and we live in the real world.

You can use

HostingEnvironment.QueueBackgroundWorkItem(ct => email.sendAsync()); 

to get something quite reliable up and running.

Upvotes: 3

Related Questions