如何获取C#中正在运行的线程的列表? [英] How do you get list of running threads in C#?
本文介绍了如何获取C#中正在运行的线程的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C#中创建动态线程,我需要获取那些正在运行的线程的状态.
I create dynamic threads in C# and I need to get the status of those running threads.
List<string>[] list;
list = dbConnect.Select();
for (int i = 0; i < list[0].Count; i++)
{
Thread th = new Thread(() =>{
sendMessage(list[0]['1']);
//calling callback function
});
th.Name = "SID"+i;
th.Start();
}
for (int i = 0; i < list[0].Count; i++)
{
// here how can i get list of running thread here.
}
如何获取正在运行的线程列表?
How can you get list of running threads?
推荐答案
创建一个List<Thread>
并将每个新线程存储在其中的第一个for循环中.
Create a List<Thread>
and store each new thread in your first for loop in it.
List<string>[] list;
List<Thread> threads = new List<Thread>();
list = dbConnect.Select();
for (int i = 0; i < list[0].Count; i++)
{
Thread th = new Thread(() =>{
sendMessage(list[0]['1']);
//calling callback function
});
th.Name = "SID"+i;
th.Start();
threads.add(th)
}
for (int i = 0; i < list[0].Count; i++)
{
threads[i].DoStuff()
}
但是,如果不需要i
,则可以将第二个循环设置为foreach
而不是for
However if you don't need i
you can make the second loop a foreach
instead of a for
作为旁注,如果您的sendMessage
函数执行时间不会很长,则应该减轻重量,然后减轻整个线程的负担,请使用任务
As a side note, if your sendMessage
function does not take very long to execute you should somthing lighter weight then a full Thread, use a ThreadPool.QueueUserWorkItem or if it is available to you, a Task
这篇关于如何获取C#中正在运行的线程的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文