Hemant Malpote
Hemant Malpote

Reputation: 891

How call async method from non async web API

I am having web api, which is non async.

From that web api, i am calling method

SmtpClient.SendMailAsync(email);

This email get sent to respective person, but the next web api request get fails.

public class TestController : ApiController
{
    public TestController(TestService testService)
    {
       _testService = testService;
    }

    public IHttpActionResult Post(data)
     {
         _testService.SendEmail(data);
     }
}

public class TestService 
{
    public async Task SendEmail(MailMessage email)
     {
        SmtpClient client = new SmtpClient();
        client.SendMailAsync(email)
     }
}

Upvotes: 1

Views: 1259

Answers (3)

Aleksandr Zolotov
Aleksandr Zolotov

Reputation: 1100

If you will need use some result of sending:

    public async IHttpActionResult Post(data)
 {
     var t = Task.Run(() =>_testService.SendEmail(data));

     var result = await t;
     // do something with result
 }

- but of course your SendEmail function should return Task<> instead of Task ...

Upvotes: 0

Sossenbinder
Sossenbinder

Reputation: 5282

Given your comment that you want to have SendEmail behave like fire & forget, I would propose using

Task.Run(() => _testService.SendEmail(data));

This will give the unit of work to the threadpool and free your request from the duty of waiting for this task. Generelly this is advised for fire & forget.

As a rule of thumb otherwise, it's generally a bad idea to call asynchronous things from a synchronous context. Do async all the way, or be prepared for deadlocking. For example, you could simply make your controller actions asynchronous as well.

Upvotes: 1

Christopher
Christopher

Reputation: 9804

From the days before the async/await pattern was introduced, there are still many non-asychronous functions around in Framework classes.

SmtpClient client is one of the classes old enough for this. The SendFunction are the droids you are look for:

https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.send

While the naming is a bit off and they return void, those seems to be the pre-async functions. Failure should be communicated via Exceptions in both cases.

Upvotes: 1

Related Questions