SendAsync呼叫会被自动取消

SendAsync呼叫会被自动取消

本文介绍了SmtpClient.SendAsync呼叫会被自动取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我称之为 smtpClient.SendAsync(...)从我的ASP.NET MVC应用程序中,异步请求被自动取消,即使 SendAsyncCancel()永远不会被调用。

Whenever I call smtpClient.SendAsync(...) from within my ASP.NET MVC application, the asynchronous requests are automatically cancelled, even though SendAsyncCancel() is never called.

同步。发送(...)的要求,而另一方面,通过就好了。

Synchronous .Send(...) requests, on the other hand, go through just fine.

我的 EmailService 服务包装处理来自我的ASP.NET MVC 3应用程序内的 SmtpClient 发送异步电子邮件。一个服务实例注入到StructureMap,它包装在使用(...){} SmtpClient 实例的每个MVC控制器C $ C>声明。

My EmailService service wrapper handles sending asynchronous email with SmtpClient from within my ASP.NET MVC 3 application. A service instance is injected into each MVC controller by StructureMap, which wraps a new SmtpClient instance in a using (...) { } statement.

下面是我的 EmailService.SendAsync 包装方法 SmtpClient

public void SendAsync(EmailMessage message)
{
    try
    {
        using (var smtpClient = new SmtpClient(_cfg.Host, _cfg.Port)
        {
            EnableSsl = _cfg.EnableSsl,
            Credentials = _credentials
        })
        {
            smtpClient.SendCompleted += new SendCompletedEventHandler(Email_OnCompleted);

            var mailMessage = new MailMessage(message.From, message.To)
                                {
                                    Subject = message.Subject,
                                    Body = message.Body
                                };

            smtpClient.SendAsync(mailMessage, message);

            _logger.Info(string.Format("Sending async email to {0} with subject [{1}]", message.To, message.Subject));
        }
    }
    catch (Exception ex)
    {
        _logger.Error("Async email error: " + ex);
        throw;
    }

}

下面是我的 Email_OnCompleted 委托:

public void Email_OnCompleted(object sender, AsyncCompletedEventArgs e)
{
    var mail = (EmailMessage)e.UserState;

    if (e.Error != null)
    {
        _logger.Error(string.Format("Error sending email to {0} with subject [{1}]: {2}", mail.To, mail.Subject, e.Error));
    }
    else if (e.Cancelled)
    {
        _logger.Warn(string.Format("Cancelled email to {0} with subject [{1}].", mail.To, mail.Subject));
    }
    else
    {
        _logger.Info(string.Format("Sent email to {0} with subject [{1}].", mail.To, mail.Subject));
    }
}

为什么异步电子邮件被取消,但同步电子邮件通过就好了?难道是一个处置问题?

Why are async emails being cancelled, but synchronous emails go through just fine? Could it be a dispose issue?

推荐答案

这绝对可以成为一个处置问题。当你处理客户端它将取消任何未完成的异步操作。

It can definitely be a dispose issue. When you dispose the client it cancels any outstanding async operations.

您应该部署在客户端在 Email_OnCompleted

You should dispose the client in Email_OnCompleted.

这是SO张贴在哪里处理?

An SO post on where to dispose: Dispose SmtpClient in SendComplete?

这篇关于SmtpClient.SendAsync呼叫会被自动取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:51