0

Suppose I have a class named `ABC'

Class ABC:IDisposable
{
    public string name {get;set;}
    public string Method1()
    {
    // Implements 
    }
    //end of class
}

I hear from other's that you should use always inherit IDisposable to free memory creating object of above class like this:

using(ABC objABC = new ABC())
{
  objABC.Method1();
}

but there is other ways to call and use above class and methods for E.g.

private string testmethods()
{
    ABC objABC = new ABC();
    string test =  objABC.Method1();
    // I want to know this above `objABC` 's memory is free after finish `testmethods()`?
    // we can also call using this like below
    string test2 = new ABC().Method1();
}

I want to know which is the best way to achieve this?

I also want to know is, is that Object memory automatically cleared after end of testmethods() calls ?

4

4 回答 4

6

假设ABC不持有任何非托管资源,则不需要实现IDisposable. 只要没有对它们的实时引用,C# 中的对象就有资格进行垃圾收集,并且当垃圾收集器运行时,它们使用的内存将被自动释放。

如果您的类IDisposable拥有需要释放的非托管资源,或者拥有其他实现IDisposable. 如果您的类拥有非托管资源,它们还应该实现一个终结器来释放它们,如果Dispose在它们被收集之前没有调用它们。

因此,第二种方法是首选的,并且在返回objABC后有资格收集objABC.Method1(实际上它可能会更早收集,尽管这是内部 GC 机制)。请注意,它不会在此时自动释放,而是仅在 GC 下一次运行时才会被释放,假设没有更多对它的引用。

于 2013-07-22T11:35:03.960 回答
5

Disposable 模式的存在是为了释放非托管资源。因此,除非您的 C# 程序调用一些本机 API,或者使用本身实现 Disposable 模式的类,否则让您的类实现 IDisposable 并始终处理它using是完全没有意义的。

于 2013-07-22T11:35:36.193 回答
2

IDisposable 接口旨在支持 Disposable 模式,该模式用于显式释放内存资源以外的资源:由于垃圾收集器 (GC) 只能处理内存,因此应显式关闭其他资源,例如打开的文件、数据库连接、各种非托管资源等.

http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

使用 IDisposable 的典型方案是

  // MyResourceWrapper is IDisposable
  using (MyResourceWrapper wrapper = new MyResourceWrapper()) { // <- acquire resource
    ... // <- work with resource
  } // <- free resource   

例如

  String text;

  using (StreamReader sr = new StreamReader(@"C:\MyText.txt")) { // resource (file stream) opened
    text = sr.ReadToEnd(); // <- resource (file stream) utilized (read)
  } // <- resource freed (file stream closed)

当您在班级中没有任何资源要释放时,您不需要实现 IDisposable

于 2013-07-22T12:09:37.487 回答
1

先问问自己——你会在问题的第二个代码部分写一个 try-finally 块吗?如果是,那么你会在 finally 块中写什么?如果您的 ABC 类正在使用非托管资源,并且它实现了 IDisposable 接口,那么您将在 finally 块中调用 Dispose 方法。

using(ABC objABC = new ABC())
{
  objABC.Method1();
}

相当于这个: -

ABC objABC = new ABC()
try
{
   objABC.Method1();
}
finally
{
   objABC..Dispose()
}

所以现在,如果你在 ABC 类中没有任何不可管理的东西,你为什么要在这个类上实现 IDisposable 接口?

具有非托管资源的类的一个示例是 SqlConnection,它实现了 IDisposable 并在其 Dispose 方法中处理所有这些非托管资源。这就是为什么你会看到人们使用如下代码:-

using (SqlConnection connection = new SqlConnection(connectionString))
{
...........
}
于 2013-07-22T13:54:30.037 回答