Afnan Bashir
Afnan Bashir

Reputation: 7419

Get Running Threads

if i run various threads by code

        var t = new Thread(() =>
        {
            try
            {
            }
            }
            catch (Exception ca)
            {
                MessageBox.Show(ca.Message);
            }
        });
        t.SetApartmentState(ApartmentState.STA);
        t.Name = "Thread1";
        t.Start()

can we have something that we can later on terminate the thread by knowing its name lets say we intend to stop thread1 or thread4 we should be able to stop it:)

Upvotes: 0

Views: 10980

Answers (4)

Cheng Chen
Cheng Chen

Reputation: 43513

Things will be quite easy if you have something like a Dictionary<string,Thread>, when you start a thread, put it in the dictionary with its name as the key. Then you can get some thread by its name using:

var t = threads["thread1"];

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

The Thread class has an Abort method which allows you to terminate the thread. This being said the proper way to terminate a thread is to use some a shared resource which indicates whether the thread should continue or stop. For example inside the thread you could implement a mechanism which tests the value of this static variable in a loop and break out of the loop. On the main thread when you decide to terminate the background thread simply set the value of the static variable and the thread will simply stop by itself.

Here's an example:

 private static volatile bool _shouldTerminate = false;

and inside the thread:

while (!_shouldTerminate)
{
    // .. do something useful
}

and when you decide to stop the thread from another thread:

_shouldTerminate = true;

Upvotes: 3

Liviu Mandras
Liviu Mandras

Reputation: 6607

You could build a Dictionary <string,Thread> . The key is the name and the value is the thread object itself. You then call Abort method on the thread object obtained from the dicitonary.

NOTE: Abort is not a very good way to end a thread. Try using some global flags.

Upvotes: 2

fejesjoco
fejesjoco

Reputation: 11903

Process.GetCurrentProcess().Threads

Or it's simpler if you have a list of threads and whenever you create a new one, you add it to your list, and you regularly remove threads that have exited. You might also need synchronization.

Upvotes: 6

Related Questions