I am trying to send an email thousands of people and log it to database in a parallel foreach loop however some of the customers received an email that has different customers' name. How can i make it thread-safe? Here is my code:
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();
}
}
}