简体   繁体   中英

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)
     }
}

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://docs.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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM