当一个C#程序持有一个命名信号量时,当应用程序被提前终止(例如通过按Ctrl+C或关闭控制台窗口),它似乎并没有释放。至少在所有进程实例终止之前都没有释放。
使用命名互斥体的情况下,在这种情况下会引发AbandonedMutexException异常,但是在信号量中不会。如何防止一个程序实例在另一个程序实例被提前终止时停顿?
使用命名互斥体的情况下,在这种情况下会引发AbandonedMutexException异常,但是在信号量中不会。如何防止一个程序实例在另一个程序实例被提前终止时停顿?
class Program
{
// Same with count > 1
private static Semaphore mySemaphore = new Semaphore(1, 1, "SemaphoreTest");
static void Main(string[] args)
{
try
{
// Blocks forever if the first process was terminated
// before it had the chance to call Release
Console.WriteLine("Getting semaphore");
mySemaphore.WaitOne();
Console.WriteLine("Acquired...");
}
catch (AbandonedMutexException)
{
// Never called!
Console.WriteLine("Acquired due to AbandonedMutexException...");
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
Thread.Sleep(20 * 1000);
mySemaphore.Release();
Console.WriteLine("Done");
}
}