GetProcessesByName will not search for threads in your application, but for processes on your computer. Actually there is no good way to get a request for threads in your own application (the question aside is the debugger).
Why can you create a wrapper class for your threads so that you can query if they are running. Or track the topics themselves in other ways .
You can also think about having a Lazy<Thread> field, which will be initialized if necessary, and you can ask if the thread will burn out. After testing, Lazy<Thread> not a good idea.
Received from Simon's answer :
private int running; public void runThread() { if (Interlocked.CompareExchange(ref running, 1, 0) == 0) { Thread t = new Thread ( () => { try { go(); } catch { //Without the catch any exceptions will be unhandled //(Maybe that what you want, maybe not*) } finally { //Regardless of exceptions, we need this to happen: running = 0; } } ); t.IsBackground = true; t.Name = "myThread"; t.Start(); } else { System.Diagnostics.Debug.WriteLine("myThreadis already Running."); } } public void go() { //My work goes here }
*: Gotta catch'em all
Wajid and Segey are right. You may have a Thread field. Let me give an example:
private Thread _thread; public void runThread() { var thread = _thread; //Prevent optimization from not using the local variable Thread.MemoryBarrier(); if ( thread == null || thread.ThreadState == System.Threading.ThreadState.Stopped ) { var newThread = new Thread(go); newThread.IsBackground = true; newThread.Name = "myThread"; newThread.Start(); //Prevent optimization from setting the field before calling Start Thread.MemoryBarrier(); _thread = newThread; } else { System.Diagnostics.Debug.WriteLine("myThreadis already Running."); } } public void go() { //My work goes here }
Note Itโs better to use the first alternative (obtained from Simonโs answer), since it is thread safe. That is, if there are several threads calling the runThread method at the same time, there is no risk of creating more than one thread.
Theraot
source share