在C#中处置非托管对象

在C#中处置非托管对象

问题描述:

假设我有一个以MyCustomDatabaseAccess作为数据成员的类。 MyCustomDatabaseAccess具有Dispose()方法。 MyCustomDatabaseAccess是访问数据库的中间件类。

Let's say I have a class that has a MyCustomDatabaseAccess as a data member. MyCustomDatabaseAccess has a Dispose() method. MyCustomDatabaseAccess is the middleware class that accesses the database.

public class MyClass {
   private MyCustomDatabaseAccess db_access;
}

MyClass是否需要实现IDisposable接口?

Does MyClass need to implement IDisposable interface?

我现在的解决方案是做这样的事情:

My solution right now is to have do something like this:

    public class MyClass {
       private MyCustomDatabaseAccess db_access;

       public void GetDBResults () {
          db_access = new MyCustomDatabaseAccess();
          DataTable dt = db_access.ExecuteStoredProc(param1, param2, etc..);

          //do stuff with results

          db_access.Dispose();

    }

}

根据我的想法在MSDN上阅读,另一种确保正确处理此对象的方法是让MyClass实现IDisposable接口,然后实现Dispose()函数,然后在调用MyClass对象的类中对其进行调用。
参阅此以获得更多信息
http:// www.devx.com/dotnet/Article/33167/0/page/3

From what I read on MSDN, another way to make sure that this object is disposed of properly would be to have MyClass implement IDisposable interface, then implement a Dispose() function, then call it in the class that calls an object of MyClass. see this for more info http://www.devx.com/dotnet/Article/33167/0/page/3

哪种方式更可取,为什么?
谢谢!

Which way is preferable and why? thanks!

我认为您只需要确保将对象丢弃即可。

I think you just need to ensure your objects are disposed.

如果您正在使用方法执行此操作,即使出现意外错误,我也认为您还可以。如果您坚持使用班级中的非托管资源,则实现IDisposable是一种确保在对象完成后有机会处置资源或为用户提供显式处置资源的方式。

if you are doing this in your method, even if there is an unexpected error, then I think you are ok. If you hold on to unmanaged resources in your class then implementing IDisposable is a way to ensure that you get a chance to dispose resources when your object is finalized, or to give your users a way to dispose of the resources explicitly.

如果您只是在方法中创建和使用资源,而不在类中保存引用,则只要确保将它们放在方法中即可(通过手动完成,或者更容易地通过将其包装在using块中),那么我想你应该没事。

If you are only creating and using the resources in a method and not holding references in the class then as long as you are ensuring they are disposed in the method (either by doing it manually , or more easily, by wrapping then in a using block), then you should be ok I think.