.NET Framework 非托管资源

示例

当我们谈论GC和“堆”时,我们实际上是在谈论托管堆托管堆上的对象可以访问不在托管堆上的资源,例如,在写入或读取文件时。当打开文件进行读取然后发生异常时,可能会发生意外行为,从而导致文件句柄无法正常关闭。因此,.NET要求非托管资源实现该IDisposable接口。该接口具有一个Dispose不带参数的单一方法:

public interface IDisposable
{
    Dispose();
}

处理非托管资源时,应确保正确处理它们。您可以通过显式调用执行此操作Dispose()在一个finally块,或者用一个using声明。

StreamReader sr; 
string textFromFile;
string filename = "SomeFile.txt";
try 
{
    sr = new StreamReader(filename);
    textFromFile = sr.ReadToEnd();
}
finally
{
    if (sr != null) sr.Dispose();
}

要么

string textFromFile;
string filename = "SomeFile.txt";

using (StreamReader sr = new Streamreader(filename))
{
    textFromFile = sr.ReadToEnd();
}

后者是首选方法,在编译过程中会自动扩展为前者。