与close()方法有关的疑问 [英] doubt related to close() method

查看:71
本文介绍了与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


这篇关于与close()方法有关的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆