0

I need to be able to make all email calls asynchronously. How do we accomplish something like that. So lets suppose I have a method A

public void A() {
    SendEmail();
}

public void SendEmail() { }

How do I make this SendEmail() method Async? DO we just do something like

public async void SendEmail() { }

Thanks.

Cory Charlton
  • 8,868
  • 4
  • 48
  • 68
JohnnyCage
  • 175
  • 1
  • 1
  • 11

3 Answers3

0

It's recommended to return a Task, so I'd return it instead of returning void:

async Task SendEmail()
{
    //Do Something
}

A Task is preferred, because you want to provide your callers (maybe yourself) to await for a Task like sending an email.

Also the task can be Continued with something else:

await SendEmail().ContinueWith(SendNotification);
avenet
  • 2,894
  • 1
  • 19
  • 26
0

Create an async wrapper

public Task void SendEmailAsyn() { 
    return Task.Factory.StartNew(() => { SendEmail(); });
}
Bjørn-Roger Kringsjå
  • 9,849
  • 6
  • 36
  • 64
XtremeBytes
  • 1,469
  • 8
  • 12
0

There is a much easier way to do asynchronous email and the tools to manage it are built right into the OS. I provided a similar answer to answer a slightly different question at: https://stackoverflow.com/a/30768906/964043

Basically, you can use System.Net.Mail.SmtpClient to quickly queue up emails which are written out to disk in a spool folder just by setting the DeliveryMethod to PickupDirectoryFromIis. On the server this is running on, you just need to setup and configure the Microsoft SMTP Service on the same machine to point to a valid SMTP server which will forward the messages for you. This means you already have a fully threaded and high performance method for sending emails asynchronously without having to write any of that code yourself. Perfect for sending messages from web applications, web services, or any other server based applications.

Community
  • 1
  • 1
dmarietta
  • 1,940
  • 3
  • 25
  • 32