c# - 当我使用 Control-C 中断 C# 控制台应用程序时会发生什么?

标签 c# .net visual-studio command-line

当我使用 Control-C 中断我的 C# 控制台应用程序时会发生什么?

进程是否被杀死?内存释放了吗? finally block 被执行了吗?数据库连接会发生什么情况?

如果应用程序是为调试或发布而构建的,或者在 Visual Studio 内部/外部运行,这是否有任何不同?

最佳答案

简短回答:在 CTRL-C 之后什么都不做

长答案:MSDN 上有一篇关于它的好文章其中明确指出,它发送信号(中断)而不是按键事件。

还有一个cancelKeyPress-Event triggered 你可以订阅它并做任何你想做的事!

不幸的是,没有更多关于默认情况下实际完成的信息。也许在最坏的情况下你可以自己检查一下。但是我应该有一些关于它的文档......

更新: Alois Kraus 写了一篇 codeproject-Article关于在收到 CTRL-C 后优雅地关闭控制台应用程序。

引用 Alois Kraus 的话:

The default behavior of the CLR is to do nothing. This does mean that the CLR is notified very late by a DLL_PROCESS_DETACH notification in which context no managed code can run anymore because the OS loader lock is already taken. We are left in the unfortunate situation that we get no notification events nor are any finalizers run. All threads are silently killed without a chance to execute their catch/finally blocks to do an orderly shutdown. I said in the first sentence default, because there is a way to handle this situation gracefully. The Console class has got a new event member with .NET 2.0: Console.CancelKeyPress. It allows you to get notified of Ctrl-C and Ctrl-Break keys where you can stop the shutdown (only for Ctrl-C, but not Ctrl-Break). The main problem here is if you catch the Ctrl-C/Break event and exit the handler there are no finalizers called. This is not what I would call a cooperative shutdown. The first thing that comes to my mind is to call Environment.Exit but it does not trigger any finalizers. All is not lost. I did come up with a dirty trick to run all finalizers: we spin up a little helper thread inside the event handler which will then call Environment.Exit. Voila, our finalizers are called.

关于c# - 当我使用 Control-C 中断 C# 控制台应用程序时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9535232/

相关文章:

c# - Entity Framework 6 插入重复值

c# - 在 DataGridView 中选择/取消选择行

c# - 需要帮助创建控件来显示数据

c# - 如何从C#中的特定资源文件中获取字符串资源

c# - Visual Studio 2013 不正确的命名空间错误

c# - Dapper 无法识别单引号中的通配符参数

c# - OpenXml 或 Microsft.Office.Interop.Excel 在 c# 中读取 excel 文件哪个更好?

java - pHash 开源感知哈希库有哪些替代方案?

c - Windows 中的混合编程

angularjs - 如何使我的 AngularJS SPA 在 VS 2015 Web 开发环境上运行正确刷新