当 C# 程序持有命名信号量时,如果应用程序提前终止(例如通过按 Ctrl+C 或关闭控制台窗口),它似乎不会被释放。至少在进程的所有实例都终止之前不会。
在这种情况下,使用命名互斥量会引发 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");
}
}
Run Code Online (Sandbox Code Playgroud)
通常,您不能保证线程在退出时释放信号量。您可以编写 try/finally 块和关键终结器,但如果程序异常终止,它们将不会总是有效。而且,与互斥体不同的是,如果一个线程在它仍然持有信号量时退出,则不会通知其他线程。
原因是.NET Semaphore 对象所基于的Windows semaphore 对象不会跟踪哪些线程已获取它,因此不能抛出类似于 .NET 信号量对象的异常AbandonedMutexException。
也就是说,您可以在用户关闭窗口时收到通知。您需要设置一个控制处理程序来侦听特定事件。您调用 Windows API 函数SetConsoleCtrlHandler,将处理您感兴趣的事件的回调函数(委托)传递给它。我已经有一段时间没有这样做了,但总的来说。
为SetConsoleCtrlHandler函数和回调创建一个托管原型:
/// <summary>
/// Control signals received by the console control handler.
/// </summary>
public enum ConsoleControlEventType: int
{
/// <summary>
/// A CTRL+C signal was received, either from keyboard input or from a
/// signal generated by the GenerateConsoleCtrlEvent function.
/// </summary>
CtrlC = 0,
/// <summary>
/// A CTRL+BREAK signal was received, either from keyboard input or from
/// a signal generated by GenerateConsoleCtrlEvent.
/// </summary>
CtrlBreak = 1,
/// <summary>
/// A signal that the system sends to all processes attached to a console
/// when the user closes the console (either by clicking Close on the console
/// window's window menu, or by clicking the End Task button command from
/// Task Manager).
/// </summary>
CtrlClose = 2,
// 3 and 4 are reserved, per WinCon.h
/// <summary>
/// A signal that the system sends to all console processes when a user is logging off.
/// </summary>
CtrlLogoff = 5,
/// <summary>
/// A signal that the system sends to all console processes when the system is shutting down.
/// </summary>
CtrlShutdown = 6
}
/// <summary>
/// Control event handler delegate.
/// </summary>
/// <param name="CtrlType">Control event type.</param>
/// <returns>Return true to cancel the control event. A return value of false
/// will terminate the application and send the event to the next control
/// handler.</returns>
public delegate bool ConsoleCtrlHandlerDelegate(ConsoleControlEventType CtrlType);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool SetConsoleCtrlHandler(
ConsoleCtrlHandlerDelegate HandlerRoutine,
bool Add);
Run Code Online (Sandbox Code Playgroud)
现在,创建您的处理程序方法:
private static bool ConsoleCtrlHandler(ConsoleControlEventType CtrlType)
{
switch (CtrlType)
{
case CtrlClose:
// handle it here
break;
case CtrlBreak:
// handle it here
break;
}
// returning false ends up calling the next handler
// returning true will prevent further handlers from being called.
return false;
}
Run Code Online (Sandbox Code Playgroud)
最后,在初始化期间,您要设置控制处理程序:
SetConsoleCtrlHandler(ConsoleControlHandler);
Run Code Online (Sandbox Code Playgroud)
现在将在用户关闭窗口时调用您的控制处理程序。这将允许您释放信号量或进行其他清理。
您可能对我的ConsoleDotNet 包感兴趣。我写了三篇关于这些东西的文章,最后两篇仍然可以在 DevSource 上找到。我不知道第一个发生了什么。
| 归档时间: |
|
| 查看次数: |
4150 次 |
| 最近记录: |