检测线程已在C#.net中运行?
我正在使用以下代码。
public void runThread(){ if (System.Diagnostics.Process.GetProcessesByName("myThread").Length == 0) { Thread t = new Thread(new ThreadStart(go)); t.IsBackground = true; t.Name = "myThread"; t.Start(); } else { System.Diagnostics.Debug.WriteLine("myThreadis already Running."); } } public void go() { //My work goes here }
我多次调用runThread()函数,但我希望线程仅在线程未运行时启动。 这怎么可能?
GetProcessesByName不会在应用程序中查找线程,而是查找计算机中的进程。 事实上,没有好的方法来获取您自己的应用程序中的线程(除了编写调试器之外)。
根据您的需要,您可以为线程创建一个包装类,以便查询它们是否正在运行。 或者通过其他方式自己跟踪线程 。
您还可以考虑在需要时初始化一个 测试后Lazy
字段,并且可以查询该线程是否存活。Lazy
不是一个好主意。
源于西蒙的答案 :
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's 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 }
*: 得抓住 所有
Wajid和Segey是对的。 你可以有一个Thread字段。 请允许我提供示例:
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 }
注意 :最好使用第一个替代(从Simon的答案派生的替代),因为它是线程安全的。 也就是说,如果有多个线程同时调用方法runThread,则不存在创建多个线程的风险。
一个简单的方法是你可以有一个标志,指示它是否正在运行。 如果发生冲突,你可能需要使用一些lock
。
public static bool isThreadRunning = false; public void runThread() { if (!isThreadRunning) { Thread t = new Thread(new ThreadStart(go)); t.IsBackground = true; t.Name = "myThread"; t.Start(); } else { System.Diagnostics.Debug.WriteLine("myThreadis already Running."); } } public void go() { isThreadRunning = true; //My work goes here isThreadRunning = false; }
您可以使用Thread.IsAlive
来检查prevoius线程是否正在运行。这是为了给出线程状态。您可以在mythread.Start().
之前进行此检查mythread.Start().
你是否只在运行线程方法中创建线程? 如果它是这样保持它作为持有runThread方法的类的字段并且询问t.IsAlive。
也许这可以帮到你
static bool isRunning = false; public void RunThread(){ if (!isRunning) { Thread t = new Thread(()=> { go(); isRunning = true;}); t.IsBackground = true; t.Name = "myThread"; t.Start(); } else { System.Diagnostics.Debug.WriteLine("myThread is already Running."); } } public void go() { //My work goes here }