如何等待MailMessage.SendAsync?

Cas*_*ton 5 c# asynchronous

如果我这样做:

public async Task<SendEmailServiceResponse> ExecuteAsync(SendEmailServiceRequest request)
    {
        ....
        var response = new SendEmailServiceResponse();
        await client.SendAsync(mail, null); // Has await
        response.success = true;
        return response;
    }
Run Code Online (Sandbox Code Playgroud)

然后我明白了:

无法等待'无效'

但如果我这样做:

public async Task<SendEmailServiceResponse> ExecuteAsync(SendEmailServiceRequest request)
    {
        ....
        var response = new SendEmailServiceResponse();
        client.SendAsync(mail, null); // No Await
        response.success = true;
        return response;
    }
Run Code Online (Sandbox Code Playgroud)

我明白了:

异步方法缺少'await'并将同步运行.

我显然缺少一些东西,只是不确定是什么.

mac*_*ura 6

正如其他人所指出的那样SendAsync有点误导.它返回一个void,而不是一个Task.如果要await发送邮件,则需要使用该方法

SendMailAsync(MailMessage message)
Run Code Online (Sandbox Code Playgroud)

要么

SendMailAsync(string from, string recipients, string subject, string body)
Run Code Online (Sandbox Code Playgroud)

这两个都返回Task并且可以等待

  • 我的答案与从 OP 的 `ExecuteAsync()` 方法中删除 `async` 关键字一样有效。我从 OP 的帖子中推断出他们想要使用异步/等待模式,因此我为 OP 提供了一个利用异步/等待模式的解决方案。 (2认同)
  • OP的问题实际上是"如何等待MailMessage.SendAsync?"**.因为不可能等待`SendAsync()`我建议OP使用4.5中添加的方法`SendMailAsync()`以便特别等待它.在任何地方我都没有建议使用`SendAsync()`是错误的,只是它无法等待(再次OP的问题专门询问如何**等待**) (2认同)