3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
該Console.CancelKeyPress事件被用于此目的。使用方法如下:
public static void Main(string[] args)
{
Console.CancelKeyPress += delegate {
// call methods to clean up
};
while (true) {}
}
當(dāng)用戶按Ctrl + C時(shí),將運(yùn)行委托中的代碼,并退出程序。這使您可以通過(guò)調(diào)用necessairy方法來(lái)執(zhí)行清理。請(qǐng)注意,執(zhí)行委托后沒有任何代碼。
在其他情況下,這也無(wú)法解決。例如,如果程序當(dāng)前正在執(zhí)行無(wú)法立即停止的重要計(jì)算。在這種情況下,正確的策略可能是在計(jì)算完成后告訴程序退出。以下代碼給出了如何實(shí)現(xiàn)的示例:
class MainClass
{
private static bool keepRunning = true;
public static void Main(string[] args)
{
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
MainClass.keepRunning = false;
};
while (MainClass.keepRunning) {
// Do your work in here, in small chunks.
// If you literally just want to wait until ctrl-c,
// not doing anything, see the answer using set-reset events.
}
Console.WriteLine("exited gracefully");
}
}
此代碼與第一個(gè)示例之間的差異e.Cancel是設(shè)置為true,這意味著在委托之后繼續(xù)執(zhí)行。如果運(yùn)行,程序?qū)⒌却脩舭碈trl +C。在這種情況下,keepRunning變量會(huì)更改值,從而導(dǎo)致while循環(huán)退出。這是使程序正常退出的一種方式。
- 3 回答
- 0 關(guān)注
- 1440 瀏覽
添加回答
舉報(bào)