How to stop multithreaded start by loop condition

This code will show you how I started several 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 am trying to stop threads before closing the application, but I do not know how to do this?

+3
source share
3 answers

One simple option is to store links to all the threads you create, and then join 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 threads to complete before the application completes.

+2
source

The cleanest and most reliable way is to make them Background Themes:

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.IsBackground = true;          // **
    thread.Start(param);
}

Background threads automatically terminate when you exit the process (main thread).

+2
source

thread.Abort();, .

I assume that you want to complete the execution and then close the application. To do this, you need to synchronize the streams using Join()or another synchronization method.

0
source

All Articles