我有一种情况,我需要同时运行一个程序的一个实例。
这将是微不足道的:
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();
}
}
除了小细节,我需要终止现有进程,而不是新进程。
我尝试制作一个信号量,在获取上述互斥锁后,现有进程可以收听,但是因为我希望它等待信号量,所以我最终可能会遇到信号量总是发出信号的情况,因此它不起作用。
任何人都知道如何解决这个问题?