3

我有一个类库项目,它有一个在对象构造期间创建文件的类。对象完成后必须删除文件。我已经实现了IDisposable并在 Dispose() 中编写了删除代码。问题是,我仍然看到文件。我记得在某处读到Dispose不能保证被调用。实现这一目标的最佳方法是什么?

4

3 回答 3

5

.NET 中的最佳实践是使用该using块。我希望您不能保证如果有人编写了孤立代码,您的代码将始终被 GC 处理;然而

使用语句

提供一种方便的语法,确保正确使用 IDisposable 对象。

通常,当您使用 IDisposable 对象时,您应该在 using 语句中声明和实例化它。using 语句以正确的方式调用对象的 Dispose 方法,并且(当您如前所示使用它时)它还会导致对象本身在调用 Dispose 时立即超出范围。在 using 块中,对象是只读的,不能修改或重新分配。

using(YourDisposable iCanDispose = new YourDisposable())
{

  // work with iCanDispose
}

将确保对象 dispose 方法在离开范围后被调用。

于 2013-11-08T00:07:19.190 回答
2

在这种情况下,using关键字是您的朋友。任何实现IDisposable的东西都可以使用它,它为您提供了一种更好的机制来确保您的对象被释放。

它的用法看起来像这样:

using (SomeIDisposableObject someThing = new SomeIDisposableObject())
{
   // Do some work here and don't sweat to much because once I fall out-of-scope
   // I will be disposed of.
}    

您也可以嵌套它们,如下所示:

using (SomeIDisposableObject someThing = new SomeIDisposableObject())
{
   // I am next up for being disposed of.
   using (SomeOtherIDisposableObject someOtherThing = new SomeOtherIDisposableObject())
   {
      // I will get disposed of first since I am nested.
   }
}

您还可以堆叠它们:

using (SomeIDisposableObject someThing = new SomeIDisposableObject())
{
   // I will be disposed of.
}

using (SomeOtherIDisposableObject someOtherThing = new SomeOtherIDisposableObject())
{
   // I will also be disposed of.
}
于 2013-11-08T00:08:38.720 回答
2

您可以在 finally 块内的任何对象(实现 IDisposable 接口)上调用 Dispose() 函数,以保证对象的破坏。

using 块可用于简化上述解决方案,而无需创建 try 和 finally 块。所以任何需要使用 using() 块的对象都应该实现 IDisposable 接口,以便对象一旦从 using 块中出来就会立即被释放。

使用语法:

using(object declaration and initialization)
{
//statements
}

using 块类似于以下内容:

try
{
//object declaration and initialization
}
finally
{
//Call Object's Dispose() 
}
于 2013-11-08T02:22:00.380 回答