用异步来点火和忘记

时间:2014-10-11 04:53:57

标签: c# asynchronous

考虑以下代码:

public async Task<Status> SendMessage(Message message)
{
    List<IMessage> _messageDispatchers = new List<IMessage>();
    try
    {
        Object[] args = new Object[] { _message };
        IMessage endpoint = (IMessage)Activator.CreateInstance(Type.GetType(_message.AgentDLLName), args);
        _messageDispatchers.Add(endpoint);

        foreach (IMessage dispatcher in _messageDispatchers)
        {
            await Task.Run(() => dispatcher.SendMessage(_message));
        }
        return await Task.Run(() => Status.Success);
    }
    catch (Exception ex)
    {
        logger.Log(LoggerLevel.Error, ex.Message);
        return Status.EmailSendingFailed;
    }

}

SendMessage:

public async Task<Status> SendMessage(OutboundMessage outboundmessage)
{
    string strMessage = string.Empty;
    string subject = string.Empty;
    MessageServices objService = new MessageServices();
    try
    {
        var config = (from SmtpConfigurationElement ms in AppConfiguration.Instance.Smtps
                      where ms.Key == "smtp"
                      select ms).Single();

        SmtpClient smtpClient = new SmtpClient(config.Host);
        smtpClient.Port = Convert.ToInt32(config.port);
        smtpClient.EnableSsl = true;
        smtpClient.Credentials = new NetworkCredential(config.UserName, config.Password);

        string[] strToList = outboundmessage.ToList.Split(';');
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(outboundmessage.FromAddress);

        if (strToList.Length > 0)
        {
            for (int j = 0; j < strToList.Length; j++)
            {
                mail.To.Add(strToList[j]);
            }
        }
        else
        {
            _LOGGER.Log(LoggerLevel.Information, "SMTP Mail Send failed as ToList is not correct");
            return Status.Failed;
        }

        if (!string.IsNullOrEmpty(outboundmessage.CCList))
        {
            string[] strCCList = outboundmessage.CCList.Split(';');
            if (strCCList.Length > 0)
            {
                for (int k = 0; k < strCCList.Length; k++)
                {
                    mail.CC.Add(strToList[k]);
                }
            }
        }

        if (!string.IsNullOrEmpty(outboundmessage.Attachments))
        {
            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(outboundmessage.Attachments);
            mail.Attachments.Add(attachment);
        }

        strMessage = await objService.ReplaceMessageWithPlaceholders(outboundmessage.PlaceholderValues, outboundmessage.MessageBody);
        subject = await objService.ReplaceMessageWithPlaceholders(outboundmessage.PlaceholderValues, outboundmessage.Subject);
        mail.Body = strMessage;
        mail.Subject = subject;
        mail.IsBodyHtml = true;
        await Task.Run(() => smtpClient.Send(mail));


        return Status.Success;
    }
    catch (Exception ex)
    {
        return Status.Failed;
    }
}

调用SendMessage:

public Status MarketingEmail(OutboundMessage _message)
{
    try
    {
        _message.MessageCreatedDate = System.DateTime.Now;
        processor.SendMessage(_message);
        return Status.Success;
    }
    catch (Exception ex)
    {
        _LOGGER.Log(LoggerLevel.Error, "Error in Marketing Email" + ex.ToString());
        return Status.InsertFailed;
    }
}

整个想法是建立一个工作流程,在这个工作流程中,发送电子邮件是最后一项任务,而且应该是一件轻松的事情。

现在对processor.SendMessage(_message)的调用有这样的建议:

  

因为没有等待此调用,所以执行当前方法   在通话结束前继续。考虑应用'await'   运算符到调用的结果。

自async&amp; amp;等待需要一起使用。

问题:

  1. 如果忽略该建议,当前的方法是否会顺利运行? (我问这个,因为它仍处于开发阶段,我现在可以改变建议的设计,而不是在以后遇到任何关键问题。)
  2. 考虑到上述要求,设计工作流程的建议最佳做法是什么?

1 个答案:

答案 0 :(得分:4)

当前的方法将“有效”,因为它将继续return Status.Success;,而无需等待processor.SendMessage(_message);的调用完成。

但是,因为那次电话被解雇了忘了,SendMessage重载没有在catch块中进行任何记录,您可能会遇到无法发送电子邮件但没有人收到通知的风险。

异步电子邮件发送的常见方法是:将电子邮件存储在其他位置(通常是邮件队列或数据库),然后设置一个单独的异步进程来读取排队的电子邮件并发送它们。如果成功,则将电子邮件标记为已发送。如果失败,它会再次尝试(直到某个时间限制或重试次数),然后如果它放弃,它可以触发通知或设置一个可以在以后检查的标志。

然后你的代码基本上会说“好吧,电子邮件已成功排队”,而不是“好的,电子邮件已发送”。将实际发送移至单独的流程更加可靠。