Get current thread by name from ProcessThreadCollection

After searching in questions and some search queries, I still do not get it.

I know that you can check if one thread is working with the Thread.isAlive () method, but I want to check if some other “FooThread” works between all running threads from the current process and If not, call the method that will run his.



 //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. } //... 

code>

Since the ProcessThread class does not have the "Name" property (for example, System.Threading.Thread), but only the ID, and I know only the name of the thread ("FooThread"), and not the identifier, how can I check if "FooThread" works / alive?

Thank you in advance

+7
multithreading c # process
source share
3 answers

As mentioned in other answers, ProcessThread and Thread objects are different. Your dll creates its own Thread object, but then it drops the reference to this object. Then, later, you request the OS (via System.Diagnostics) for this stream and expect the same access level as before as the creator of the stream.

Instead, you should save references to Thread objects when they are created. Perhaps your dll could implement a public object of a static collection that would then add your stream objects when they were created.

Then, outside of your DLL, you can scroll through the collection and check the names and status of each thread.

+5
source share

ProcessThread represents a thread at the operating system level, and Thread represents a managed .Net thread. The operating system thread does not have a name, but a unique identifier (like a process).

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

+3
source share

I don’t think there is a way to do this. A ProcessThread is an OS thread. A Thread represents a managed thread inside your application. There is no connection between them. In addition, the display of Thread and ProcessThread not 1: 1, as in, a ProcessThread can represent several Thread s.

+2
source share

All Articles