同時に実行するプログラムのインスタンスを 1 つだけにする必要がある状況があります。
これは次のように簡単です。
class OneAtATimePlease
{
static void Main()
{
// Naming a Mutex makes it available computer-wide. Use a name that's
// unique to your company and application (e.g., include your URL).
using (var mutex = new Mutex (false, "oreilly.com OneAtATimeDemo"))
{
// Wait a few seconds if contended, in case another instance
// of the program is still in the process of shutting down.
if (!mutex.WaitOne (TimeSpan.FromSeconds (3), false))
{
Console.WriteLine ("Another app instance is running. Bye!");
return;
}
RunProgram();
}
}
static void RunProgram()
{
Console.WriteLine ("Running. Press Enter to exit");
Console.ReadLine();
}
}
小さな詳細を除いて、新しいプロセスではなく、既存のプロセスを終了する必要があります。
上記のミューテックスを取得した後、既存のプロセスがリッスンできるセマフォを作成しようとしましたが、セマフォを待機させたいため、セマフォが常に通知され、機能しない状況に陥る可能性があります。
誰でもこの問題を解決する方法について良い考えを持っていますか?