可能会跳过“finally”代码块的原因是什么?

发布于 2024-12-12 01:49:17 字数 320 浏览 0 评论 0原文

我正在重构我的 Windows 服务,以便对命名的 Mutex 的访问集中在工作线程的方法中。现在应该在finally 块中释放它,而不是在OnStop()~DerivedService() 中释放它。

我观察到,当我按 Shift+F5 停止调试时,会跳过析构函数调用,并且预计崩溃(比礼貌地引发异常更严重)将是跳过 finally 块的唯一原因。

当我编写服务及其工作线程时,我希望在替换服务代码、登录和注销、附加调试器等繁琐的道德之前清除这里的任何令人讨厌的意外。

谢谢。

I am refactoring my Windows Service so that access to the named Mutex is centralized in the worker thread's method. Instead of releasing it in OnStop() and ~DerivedService() it now should be released in the finally block.

I've observed skipping of destructor calls when I hit Shift+F5 to stop debugging and expect that and a crash (more serious than politely raising an exception) would be the only reasons to skip the finally block.

As I am coding a Service and its worker thread I was hoping to clear up any nasty surprises here before the rigmorale of replacing service code, logging in and out, attaching debugger etc.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

述情 2024-12-19 01:49:17

Windows 互斥体中有一个内置机制可以处理程序或线程意外结束的情况,而不释放互斥体。如果当前持有互斥锁的线程退出,互斥锁将自动解锁,但处于特殊的放弃状态。

不要过多关注清理工作,而是在获取互斥锁并放弃其状态时制定一个特殊的例程。在这种情况下,您可能应该对受保护的资源进行一些额外的一致性检查 - 它可能处于任何状态。

There is a built in mechanism in the Windows Mutexes to handle the situation where a program or thread ended unexpectedly, without releasing the mutex. If the thread currently holding the mutex quits, the mutex will become unlocked automatically, but in a special abandoned state.

Instead of focusing too much on cleaning up, make a special routine whenever the mutex is acquired and its state is abandoned. In that case you should probably do some extra consistency checks on the protected resource - it could have been left in any state.

伤痕我心 2024-12-19 01:49:17

最终块无法执行的原因有很多(实际上有几个)。一般来说,如果您调用Environment.FailFast,一些异步异常(< code>StackOverflowException、ExecutingEngineException)、暴力关闭您的 PC :-) 以及(经常被遗忘)如果终结器方法中有异常

请阅读此处的示例C#“finally”块是否始终执行?在C#中,如果抛出未处理的异常,Finally块会在try、catch、finally中执行吗?

There are many (in reality a few) reasons why a final block won't execute. In general if you call Environment.FailFast, some asynchronous exceptions (StackOverflowException, ExecutingEngineException), shutting down violently your PC :-), and (often forgotten) if there is an exception in a finalizer method

Read for example here Does the C# "finally" block ALWAYS execute? and In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文