cezarlamann
cezarlamann

Reputation: 1523

Get running thread by name from ProcessThreadCollection

After searching on Stack Overflow questions and some googling, I still not getting it.

I'm aware that you can check if a single thread is running with "Thread.isAlive()" method, but I want to check if a particular "FooThread" is still running between all running threads from current process, and if not, call the method that starts it.

//somewhere in the code, on another Project/DLL inside solution
private void FooThreadCaller()
{
    Action act = () => fooFunction();
    Thread t = new Thread(new ThreadStart(act));
    t.Name = "FooThread";
    t.Start();
}
//...
Process proc = System.Diagnostics.Process.GetCurrentProcess();
ProcessThreadCollection threads = proc.Threads;
bool ThreadExists = false
foreach (ProcessThread item in threads)
{
    // if item.Name == "FooThread", then ThreadExists = true...
    // so, if !ThreadExists then call FooThreadCaller() and so on.
}
//...

Since the ProcessThread class doesn't have a "Name" property (like System.Threading.Thread does) but only ID, and I only know the thread name ("FooThread") not the ID, how could I check if "FooThread" is running/alive?

Thank you in advance

Upvotes: 10

Views: 14672

Answers (3)

Slider345
Slider345

Reputation: 4758

As mentioned in the other answers, the ProcessThread and the Thread objects are different. Your dll is creating it's own Thread object, but then it throws away it's reference to that object. Then later on your are querying the OS (through System.Diagnostics) for that thread and expecting the same level of access you had before as the thread's creator.

Instead, you should save the references to your Thread objects as you create them. Maybe your dll could implement a public static collection object which you would then add your thread objects to as you create them.

Then outside of your dll you could loop through the collection and check the names and status of each Thread.

Upvotes: 6

ken2k
ken2k

Reputation: 48975

ProcessThread represents an operating system-level thread, while Thread represents a .Net managed thread. An operating system-level thread doesn't have a name but a unique ID (just like a process does).

Instead of checking in the list of current thread if your thread is still running, you probably should change the logic of your code. For example, you could keep a boolean containing the state of your thread and update it when it starts/ends.

Upvotes: 3

Vlad
Vlad

Reputation: 1919

I don't think there is a way to do that. A ProcessThread represents an OS thread. A Thread represents a managed thread inside your application. There isn't really a relationship between the two. Furthermore, the mapping of Thread and ProcessThread is NOT 1:1, as in, a ProcessThread can represent multiple Threads.

Upvotes: 2

Related Questions