foreach循环内的线程在C# [英] Threads inside a foreach loop in c#

查看:501
本文介绍了foreach循环内的线程在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code在我的asp.net web应用程序发送不同的邮件到用户不同的充

 的foreach(DataRow的数据行的dataTable.Rows)
{
   sendMails();
}
公共无效sendMails()
{
 //邮件code
}

现在我想使用foreach循环内的线程,但我不知道会是什么结果,因为如果我开始'N'发生了什么线程池中的线程数..再看看我的数据表中包含1000行,

是否有可能有1000个线程同时运行?

 的foreach(DataRow的数据行的dataTable.Rows)
{
    TS1的ThreadStart =新的ThreadStart(sendMails);
    线程线程1 =新主题(TS1);
    thread1.Start();
}公共无效sendMails()
{
   //邮件code
}


解决方案

启动一个线程,会做所有发送邮件的工作:

 新的Thread(()=> {
    的foreach(DataRow的数据行的dataTable.Rows)
    {
        sendMails();
    }
})。开始();

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
}

解决方案

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

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

这篇关于foreach循环内的线程在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆