Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads inside a foreach loop in c#

Hai guys,

I had the following code to send different mails to differnt users in my asp.net web application

foreach (DataRow dataRow in dataTable.Rows) 
{
   sendMails();
}
public void sendMails()
{
 //mail code
}

Now i want to use threads inside foreach loop, but i dont know what would be the result because if i start 'n' number of threads what happens to the thread pool.. Consider my datatable contains 1000 rows,

Is it possible to have 1000 threads running concurrently?

foreach (DataRow dataRow in dataTable.Rows) 
{
    ThreadStart ts1 = new ThreadStart(sendMails);
    Thread thread1 = new Thread(ts1);
    thread1.Start();
}

public void sendMails()
{
   //mail code
}
like image 629
ACP Avatar asked Jan 05 '10 11:01

ACP


4 Answers

Start a single thread that will do the job of sending all mails:

new Thread(() => {
    foreach (DataRow dataRow in dataTable.Rows) 
    {
        sendMails();
    }
}).Start();
like image 93
Darin Dimitrov Avatar answered Sep 25 '22 14:09

Darin Dimitrov


Using the code you've got, nothing would happen to the threadpool - you'd be creating new threads completely outside the threadpool.

Are you really sure you want to use a thread per mail - or even multiple threads at all? I'd imagine you'll be limited by your connection to the local SMTP server, and starting multiple threads isn't going to help that.

Starting a single thread to send everything in the background (as per Darin's suggestion) is more sensible, if the purpose of using threads is to be able to return a page to the user saying "Yes, I'm now sending mails." On the other hand, it does mean that if that process stops for whatever reason, you could end up having only sent half of them. An alternative (as suggested by Charlie) would be to use a queuing system (a file, database or MSMQ for example). That way you could block until you'd queued all the mails, meaning that when you return to the user you can be confident that the data is "safe" - but you could do the actual mail sending in the background with a service which could be more robust.

like image 38
Jon Skeet Avatar answered Sep 24 '22 14:09

Jon Skeet


Would it not be more sensible to look at using a message queue with a seperate windows service to send the emails?

like image 26
Charlie Avatar answered Sep 25 '22 14:09

Charlie


Don't create your own threads, having 1000 threads will mean the CPU spending all it's time switching between them and very little time actually executing any work.

Use the threadpool to do this, it will execute up to 25 (by default) background threads and can automatically block when they're all busy.

See MSDN tutorial

like image 40
Paolo Avatar answered Sep 22 '22 14:09

Paolo