Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop multithread start by for loop condition

This code will show you how I started multiple threads:

for (int i = 0; i < 8; i++)
{
    doImages    = new DoImages(this, TCPPORT + i);
    var thread  = new Thread(doImages.ThreadProc);
    thread.Name = "Imaging";
    var param = (i + 1).ToString();                      
    thread.Start(param);
}

Now I'm trying to stop the threads before closing my application but I don't know how to do that?

like image 655
TuanTDA Avatar asked Dec 02 '25 14:12

TuanTDA


1 Answers

One simple option is to store references to all of the threads that you spawn and then join all of them when you are done:

Thread[] threads = new Thread[8];
for (int i = 0; i < 8; i++)
{
    doImages    = new DoImages(this, TCPPORT + i);
    var thread  = new Thread(doImages.ThreadProc);
    threads[i] = thread;
    thread.Name = "Imaging";
    var param = (i + 1).ToString();                    
    thread.Start(param);
}
for (int i = 0; i < 8; i++)
{
    threads[i].Join();
}

This will wait for all of the threads to finish before the application terminates.

like image 103
murgatroid99 Avatar answered Dec 04 '25 06:12

murgatroid99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!