I try to use the asynchronous SendAsync method of SmtpClient

 public async Task SentMessageAsync(ApplicationUser user, string title, string text) { MailMessage mail = new MailMessage(SiteFromAdress, new MailAddress(user.Email)); mail.IsBodyHtml = true; mail.Subject = title; mail.Body = text; await smtpClient.SendAsync(mail, new object()); } 

Where await smtpClient.SendAsync studio swears on ожидание 'void' невозможно .

Is it possible to do sending emails asynchronously? And why the studio swears?

    2 answers 2

    The fact is that this is an asynchronous method from the old EAP model (event-based asynchronous programming). The SendAsync() method simply starts sending and exits. You can learn about the end of sending by subscribing to the SendCompleted event. From MSDN :

     SmtpClient client = new SmtpClient(args[0]); client.SendCompleted += SendCompletedCallback; client.SendAsync(message, userState); ... private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { ... } 

    If you want to use async / await, use the SendMailAsync() method.

      It turned out that smtpClient.SendAsync is an outdated feature.

      instead, you must use smtpClient.SendMailAsync(mail) and it already returns Task and you can work asynchronously with it.