不要IDisposable的对象得到处理,如果该程序意外关闭的? [英] Do IDisposable objects get disposed of if the program is shut down unexpectedly?

查看:225
本文介绍了不要IDisposable的对象得到处理,如果该程序意外关闭的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果程序意外退出,会发生什么(无论是异常或终止处理)?是否有这样的(或其他方式),其中程序将终止任何情况下,但的IDisposable 对象将不会被妥善处置?

What happens if the program exits unexpectedly (either by exception or the process is terminated)? Are there any situations like this (or otherwise) where the program will terminate, but IDisposable objects won't be properly disposed of?

我问的原因是因为我在写代码,将与周边沟通,我希望确保有没有机会,它会在一个糟糕的状态。

The reason I'm asking is because I'm writing code that will communicate with a peripheral, and I want to make sure there's no chance it will be left in a bad state.

推荐答案

如果病因是一个例外,一个使用块或<$ C $内抛出C>尝试捕捉终于块,它将被处置,因为它应该。如果不是被逮住使用阻止它不会自动处理(如在应用程序关闭正确它不会做)。

If the cause is an exception and thrown from within a using block or a try catch finally block, it will be disposed as it should. If it is not catched by a using block it is not disposed automatically (like it doesn't do when the application closes properly).

一个例子:

IDisposable d1 = new X();

using (IDisposable d2 = new X())
{
    throw new NotImplementedException();
}

d1.Dispose();



D 1 未设置, D 2 通常。有些类型的异常可能会阻止使用块,还有一些程序崩溃的处理。如果原因是电源故障或系统崩溃,没有什么可以做,无论是当然。

d1 is not disposed, d2 usually is. Some types of exceptions may prevent handling of using blocks and also some program crashes. If the cause is a power failure or system crash, there is nothing you can do either of course.

这篇关于不要IDisposable的对象得到处理,如果该程序意外关闭的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆