How do you get list of running threads in C#?

后端 未结 5 1066
眼角桃花
眼角桃花 2021-02-01 11:12

I create dynamic threads in C# and I need to get the status of those running threads.

List[] list;
list = dbConnect.Select();

for (int i = 0; i &l         


        
5条回答
  •  野的像风
    2021-02-01 11:37

    Create a List and store each new thread in your first for loop in it.

    List[] list;
    List threads = new 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();
        threads.add(th)
    }
    
    for (int i = 0; i < list[0].Count; i++)
    {
        threads[i].DoStuff()
    }
    

    However if you don't need i you can make the second loop a foreach instead of a for


    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

提交回复
热议问题