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
Perhaps would be more sensible to use the Thread Pool for that, or even Parallel Linq, which comes in .NET 4.0 (or in Parallel FX):
dataTable.Rows.AsParallel().Select(a =>
{
//mail code
return null;
});
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
First point is that if you explicitly create threads like this, you aren't using the thread pool. The CLR will oblige by creating all these threads, even though it'll ultimately create far too many and drag itself down. 1000 explicit threads is way too many.
Are you trying to do this on another thread because you want it to happen asynchronously, or becuase you actually want multiple threads doing the sends?
If the former, then try something like:
ThreadStart ts1 = new ThreadStart(sendMails);
Thread thread1 = new Thread(ts1);
thread1.Start();
public void sendMails()
{
foreach (DataRow dataRow in dataTable.Rows)
{
//mail code
}
}
If you do feel that sending performance will be improved with some multithreading, then you'll need to manually throttle the number of threads created at any one time, or use the .Net thread pool, as this will let you queue up work items which will block until a thread becomes free. This is certainly preferable to creating loads of explicit threads.
Thread per email is not the best idea as explained why by many, however in case you decided to create one background thread to handle all emails, the thread run time will be limited to 110 seconds. ASP.NET limits thread execution by default to 110 seconds in .NET 2.0. http://msdn.microsoft.com/en-us/library/e1f13641(v=vs.80).aspx
Creating a queue - as suggested by others in earlier replies - is more sensible and scalable.
http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.executiontimeout.aspx
It would probably be better to structure your method like this:
public void SendMails(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
// send emails
}
}
And then call it like this:
SendMails(dataTable);
Or call the method with a BackgroundWorker
so that your UI doesn't lock up.
Would it not be more sensible to look at using a message queue with a seperate windows service to send the emails?