Search code examples
c#parallel-processing.net-4.0parallel.foreach

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<EmailService.MailAddress>(System.Collections.Generic.IEnumerable<EmailService.MailAddress>, System.Action<EmailService.MailAddress>)' has some invalid arguments

Argument 1: cannot convert from 'EmailService.MailAddressCollection' to 'System.Collections.Generic.IEnumerable<EmailService.MailAddress>'

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;
    } 
}

Solution

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