此时无法启动异步操作

An asynchronous operation cannot be started at this time

我正在使用以下代码行调用异步操作:

Task.Run(() => { _emailService.SendEmail(email); }).Wait();


public async Task<bool> SendEmail(EmailTemplate email)
{
    try
    {
        using (Client)
        {
            await Client.SendMailAsync(email.Message);
            return true;
        }
    }
    catch (Exception ex)
    {
        Logger.Fatal(ex.ToString(), "Error occurred while sending an Email.");
        return false;
    }
}

当代码 运行 第一次运行时,它没有问题,我收到了我的电子邮件,但是当我每隔一段时间 运行 它时,因为我收到以下 2 个错误:

2016-02-04 15:50:05.3039 [11] FATAL ExceptionHandling.Models.EmailService+d__0.MoveNext - System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Mail.SmtpClient'. at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken) at System.Net.Mail.SmtpClient.SendMailAsync(MailMessage message) at ExceptionHandling.Models.EmailService.d__0.MoveNext()

2016-02-04 16:33:09.9768 [9] FATAL ExceptionHandling.Models.EmailService+d__0.MoveNext - System.Net.Mail.SmtpException: Failure sending mail. ---> System.InvalidOperationException: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.

我想了解为什么在第一次尝试后会出现上述错误?

您的错误可能(至少部分)是由于您处置了 Client

using 语句的范围 之外 处理实例化的对象是对关键字的一种非常非常规的用法,很容易出错。

一个简单的解决方法是每次都创建一个新的客户端实例:

using (MailClient client = CreateMailClient())
{
    await client.SendMailAsync(email.Message);
    return true;
}

private SmtpClient CreateMailClient()
{
    MailClient client = new MailClient();

    // Configure client.

    return client;
}