gpt4 book ai didi

c# - 检测控制台应用程序何时关闭/终止?

转载 作者:IT王子 更新时间:2023-10-29 04:34:55 27 4
gpt4 key购买 nike

我想为我的控制台应用程序安全退出,该应用程序将使用单声道在 linux 上运行,但我找不到解决方案来检测信号是否发送到它或用户是否按下了 ctrl+c。

在 Windows 上有内核函数 SetConsoleCtrlHandler 可以完成这项工作,但它不适用于单声道。

如何在我的控制台应用程序上获得关闭事件以安全退出它?

最佳答案

您需要使用 Mono.UnixSignal,Jonathan Pryor 发布了一个很好的示例:http://www.jprl.com/Blog/archive/development/mono/2008/Feb-08.html

Mono 页面上还有一个较短的示例:FAQ / Technical / Operating System Questions / Signal Handling :

// Catch SIGINT and SIGUSR1
UnixSignal[] signals = new UnixSignal [] {
new UnixSignal (Mono.Unix.Native.Signum.SIGINT),
new UnixSignal (Mono.Unix.Native.Signum.SIGUSR1),
};

Thread signal_thread = new Thread (delegate () {
while (true) {
// Wait for a signal to be delivered
int index = UnixSignal.WaitAny (signals, -1);

Mono.Unix.Native.Signum signal = signals [index].Signum;

// Notify the main thread that a signal was received,
// you can use things like:
// Application.Invoke () for Gtk#
// Control.Invoke on Windows.Forms
// Write to a pipe created with UnixPipes for server apps.
// Use an AutoResetEvent

// For example, this works with Gtk#
Application.Invoke (delegate () { ReceivedSignal (signal); });
}});

关于c# - 检测控制台应用程序何时关闭/终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6546509/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com