Threads inside a foreach loop in c#

前端 未结 8 1505
粉色の甜心
粉色の甜心 2020-12-31 23:52

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         


        
相关标签:
8条回答
  • 2021-01-01 00:11

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

    new Thread(() => {
        foreach (DataRow dataRow in dataTable.Rows) 
        {
            sendMails();
        }
    }).Start();
    
    0 讨论(0)
  • 2021-01-01 00:11

    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.

    0 讨论(0)
提交回复
热议问题