[英]Detecting a Thread is already running in 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<Thread>
字段,該字段將在需要時進行初始化,您可以查詢該線程是否存活。
Lazy<Thread>
不是一個好主意。
源於西蒙的答案 :
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.