并行Foreach循环奇数行为

时间:2016-04-12 13:20:39

标签: c# model-view-controller parallel.foreach

我正在尝试向成千上万的人发送电子邮件,并在并行的foreach循环中将其记录到数据库中,但是有些客户收到的电子邮件中有不同的客户'名称。我如何使其线程安全?这是我的代码:

EmailEntities db = new EmailEntities();
string templateData ="";
MailHelper mh = new MailHelper();
List<Customers> allCustomers = db.Customers.ToList<Customers>();

Parallel.ForEach(allCustomers, customer =>
{
    string[] emails = customer.EmailAddress.Split(';');

    foreach (var mailItem in emails)
   {

        string email = mailItem.Trim();
        templateData = mailEntitiyData.HtmlContent;             
        templateData = templateData.Replace("##FULL_NAME##", customer.Name + " " + customer.Surname);
        var postRes = mh.SendMail(subject, templateData , email, postType, null, null, bytes);
        Logger.Log(customer.ID, email, postRes.PostID);
   }

});


 public static class Logger
{
    public static void Log( int CustomerID, string email, string messageID)
    {
        using (EmailMarketingEntities db = new EmailMarketingEntities())
        {
            MailLogs ml = new MailLogs();
            ml.CustomerID = CustomerID;              
            ml.EmailAddress = email;
            ml.MessageID = messageID;               
            db.MailLogs.Add(ml);
            db.SaveChanges();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

使用此:

foreach (var mailItem in emails)
{

    string email = mailItem.Trim();
    templateData = mailEntitiyData.HtmlContent;             
    templateData = templateData.Replace("##FULL_NAME##", customer.Name + " " + customer.Surname);
    var postRes = mh.SendMail(subject, templateData , email, postType, null, null, bytes);
    Logger.Log(customer.ID, email, postRes.PostID);
}

您实际上正在重写mailEntitiyData.HtmlContent内容,这绝对不是您想要做的。将其更改为:

foreach (var mailItem in emails)
{

    string email = mailItem.Trim();
    templateData = mailEntitiyData.HtmlContent;             
    var customTemplateData = templateData.Replace("##FULL_NAME##", customer.Name + " " + customer.Surname);
    var postRes = mh.SendMail(subject, customTemplateData, email, postType, null, null, bytes);
    Logger.Log(customer.ID, email, postRes.PostID);
}

应解决您的问题。