parallel.foreach with custom collection
I am extending the System.Net.Mail.MailAddress
class to include an ID field, so I created a new custom MailAddress
class that inherited from the existing class and a new custom MailAddressCollection
class. I then overrode the existing System.Net.Mail.MailMessage.To
to use my new collection.
I would like to process the recipients in parallel, but I can't get the syntax right. This is the syntax I am using.
Parallel.ForEach(EmailMessage.To, (MailAddress address) =>
{
emailService.InsertRecipient(emailId, address.DisplayName, address.Address, " ");
});
I get the following errors:
The best overloaded method match for 'System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable, System.Action)' has some invalid arguments
Argument 1: cannot convert from 'EmailService.MailAddressCollection' to 'System.Collections.Generic.IEnumerable'
What syntax do I need to use custom collections?
Here is the EmailService.MailAddress class:
public class MailAddress : System.Net.Mail.MailAddress
{
/// <summary>
/// Contains an identifier of the address for use in sending unique email links.
/// </summary>
public string ID = "";
public MailAddress(string Address) : base(Address)
{
}
public MailAddress(string Address, string Nam开发者_如何学Ce): base(Address, Name)
{
}
public MailAddress(string Address, string Name, string Id) : base(Address, Name)
{
ID = Id;
}
}
Well, we don't know what EmailService.MailAddressCollection
actually implements. If it only implements the non-generic IEnumerable
interface, you could try this:
Parallel.ForEach(EmailMessage.To.Cast<MailAddress>(), address =>
{
emailService.InsertRecipient(emailId, address.DisplayName,
address.Address, " ");
});
You don't need to do this. The SmtpClient class already has a SendAsync method.
I was complicating the issue. I ended up using Parallel.For with a counter instead of ForEach.
System.Threading.Tasks.Parallel.For(0, EmailMessage.To.Count,
i => emailService.InsertRecipient(emailId, EmailMessage.To[i].DisplayName,
EmailMessage.To[i].Address, EmailMessage.To[i].Id));
精彩评论