I would like to ask is this code thread safe? There is a problem with attachment object. It is passed by reference to the new thread where MailHelper use it and sometimes the attachment object is mixed between threads.
public static void Start()
{
foreach (var message in messages)
{
//skip code
var fileName = httpWebResponse.GetResponseHeader("filename");
var fileStream = httpWebResponse.GetResponseStream();
var attachment = new Attachment(fileStream, fileName);
var thread = new Thread(() =>
{
var dictionary = new ListDictionary
{
{ "$Url$", message.Url }
};
MailHelper.SendMessage(dictionary,
message.Mail.Headers.From.Address,
"EmailConvertSuccess.txt",
attachment)
});
thread.Start();
}
}
No this will probably not be working – but it’s not only the attachment (see Darins answer) but the
messageobject you use as an iterator as well – you will have to copy it to a local instance before calling your Thread like this:If you really want to you could pass this as parameter – just like Darin did with it’s variant but I don’t think this is really needed)