Sam Reina
Sam Reina

Reputation: 305

multi threads for sending emails

I have a listview with the names of the email lists (on import it is adding the path and the name). I have another listview with smtp servers with 5 columns: ip, port, user, pass, type (normal, ssl, tls) a backgroundworker for progress bar purposes.

int cnt = this.listView1.CheckedItems.Count;//email lists
            for (int i = 0; i < cnt; i++)
            {
                startsend();
            }

so for each list of emails in the listView1 it will do the function.

but I don't know how to make the function to use 20-30 threads and also use all the smtp servers(not random) I have in listView2 (checkeditems) to send the emails. I have only 3 smtp servers but I still wanna use 20 threads.

I tried to find a solution to this for more than a week but I couldn't. I saw that here are many experts and maybe you can help a n00b user.

How can I send the emails from each listView1.CheckedItems using smtp servers which are rotated from listView2.CheckedItems and also using 20-30 threads ? Thank you!

Upvotes: 1

Views: 1578

Answers (1)

Tudor
Tudor

Reputation: 62439

First off, you should use foreach for this task, it's much more readable. So first you can iterate over the servers, then over the email lists and in the inner loop send mails in parallel:

ThreadPool.SetMinThreads(20, 20);
int activeWorkers = 0;
object signal = new object();

foreach(/* server in listView2 */)
{
    foreach(/* email in listView1 */)
    {
        lock(signal) ++activeWorkers; // keep track of active workers

        ThreadPool.QueueUserWorkItem(
            o =>
            {
                string email = (string)o;
                startsend(server, email);                   

                lock(signal) // signal termination
                {
                   --activeWorkers;
                   Monitor.Pulse(signal);                    
                }
            }, email);

        lock(signal) 
        {
           while(activeWorkers > 0) // improvised barrier
               Monitor.Wait(signal);
        }
    }
}

Upvotes: 1

Related Questions