编写这个函数没有内存泄漏! - 请指教
在下面的代码示例中,filestream和streamreader会被释放还是会造成内存泄漏?是否可以在不导致内存泄漏的情况下编写此函数?
string ReadFile(string strPath)
{
using (FileStream fstream = new FileStream(strPath, FileMode.Open))
{
using (StreamReader sreader = new StreamReader(fstream))
{
return sreader.ReadToEnd().ToString(); //NOTE ITS RETURNED HERE...SO CAN IT GET DISPOSED AFTER THIS LINE?
}
}
}
谢谢
In the following code example,will filestream and streamreader get disposed or will they create memory leaks? Is it possible to code this function without causing memory leaks?
string ReadFile(string strPath)
{
using (FileStream fstream = new FileStream(strPath, FileMode.Open))
{
using (StreamReader sreader = new StreamReader(fstream))
{
return sreader.ReadToEnd().ToString(); //NOTE ITS RETURNED HERE...SO CAN IT GET DISPOSED AFTER THIS LINE?
}
}
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
using
指令的意思是:所以,是的,
fstream
和sreader
都将被处置。using
directive means:So yes both
fstream
andsreader
will be disposed.无论实例化方法是否在块内返回,
using
指令都会调用 Dispose() 方法。但请注意,您可以使用 System.IO.File.ReadAllText 方法以更少的代码实现相同的目的:
The
using
directive calls the Dispose() method regardless whether the instantiating method returns within the block or not.Please note, however, that you could use the
System.IO.File.ReadAllText
method to achieve the same with less code: