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は正しいです。スレッドフィールドを持つことができます。例を挙げさせてください。
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を同時に呼び出すさまざまなスレッドがある場合、複数のスレッドが作成されるリスクはありません。