与close()方法有关的疑问

与close()方法有关的疑问

问题描述:

据我了解,dispose()方法用于为非托管资源分配内存空间.

现在,当我们创建streamreader类的对象时,我们可以多次调用close方法(即,我们可以打开和关闭多个文件).
例如

As per my understanding, dispose() method is used to deallocate memory space for unmanaged resources.

Now when we create an object of streamreader class, we can call close method multiple time(i.e. we can open and close multiple file).
e.g.

StreamReader sreader=new StreamReader("a.txt");
...
sreader.Close();
sreader=new StreamReader("b.txt");
...
sreader.Close();



现在在上面的代码中,如果我没有调用sreader.Dispose(),那么将使用finalize()方法(即通过垃圾回收器)进行内存释放,否则将导致任何内存泄漏.

如果您有任何想法,请告诉我.



Now in above code if I didn''t call sreader.Dispose(), then does memory deallocation will occur using finalize() method(i.e. by garbage collector) or does it will going to create any memory leaks.

Please let me know if you have any idea.

通常,FinalizeDispose无关.您无需像GC一样调用Finalize,但是您需要为实现此接口的所有对象调用Dispose.根据 http://msdn,对Close的调用将调用Dispose(true). .microsoft.com/en-us/library/system.io.streamreader.close.aspx [
Generally, Finalize has nothing to do with Dispose. You never need to call Finalize as GC does it, but you need to call Dispose for all object implementing this interface. The call to Close calls Dispose(true), according to http://msdn.microsoft.com/en-us/library/system.io.streamreader.close.aspx[^].

Calling this method is important to free unmanaged resources and especially important for StreamWriter (otherwise you can loose the results of writing), so the call should be done in finally part of try-finally block:

sreader=new StreamReader("b.txt");
try {
   //...
} finally {
   sreader.Close();
}



—SA



—SA