异步模块或处理程序已完成,而异步操作仍处于挂起状态



我有以下内容用于发送电子邮件,这很有效:

    private SmtpClient _client = new SmtpClient("smtp.gmail.com", 587)
    {
        Credentials = new NetworkCredential("address@gmail.com", "password"),
        EnableSsl = true
    };
    public void DoThis(){
    _client.Send("from@gmail.com", to.Email, "Subject", "Body");}
    public void DoThat(){
    _client.Send("from@gmail.com", to.Email, "Subject", "Body");}

但是在发送电子邮件之前它阻止了Web应用程序,因此我决定尝试异步发送:

   public void DoThis(){
    var message = new MailMessage("from@gmail.com", to.Email, "Subject", "Body");
   _client.SendAsync(message, null);
   }

如果我调试,我可以看到异步处理,但我总是得到以下内容:

异步

模块或处理程序在异步时完成 行动仍在等待中。

我做错了什么?

我最终重新设计了我的异步电子邮件的发送方式,如下所示:

public void SendAsyncEmail(MailMessage message)
        {
            var client = new SmtpClient("mail.hover.com", 587)
            {
                Credentials = new NetworkCredential("admin@site.com", "Covert00!"),
                EnableSsl = false
            };
            client.SendCompleted += (sender, error) =>
            {
                if (error.Error != null)
                {
                    // TODO: get this working
                    throw new WarningException("Email Failed to send.");
                }
                client.Dispose();
                message.Dispose();
            };
            ThreadPool.QueueUserWorkItem(o => client.SendAsync(message, Tuple.Create(client, message)));
        }

请注意,这是一个临时解决方案,处理电子邮件的正确方法(似乎)是使用某种与辅助角色或其他 Windows 服务配对的队列服务来弹出消息。

相关内容

最新更新