views:

116

answers:

3

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 Name): base(Address, Name)
    {

    }

    public MailAddress(string Address, string Name, string Id) : base(Address, Name)
    {
        ID = Id;
    } 
}
+1  A: 

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, " ");
});
Jon Skeet
I added the mail address class.
SchwartzE
A: 

You don't need to do this. The SmtpClient class already has a SendAsync method.

Esteban Araya
This isn't the already made service. This is a custom service to do additional features.
SchwartzE
A: 

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));
SchwartzE