编写这个函数没有内存泄漏! - 请指教

发布于 2024-09-10 17:31:45 字数 482 浏览 1 评论 0原文

在下面的代码示例中,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饭团 2024-09-17 17:31:45

using 指令的意思是:

try
{
var iDisposable = new IDisposable();
//using iDisposable...
}
finally
{
//here IDisposable's dispose
}

所以,是的,fstreamsreader 都将被处置。

using directive means:

try
{
var iDisposable = new IDisposable();
//using iDisposable...
}
finally
{
//here IDisposable's dispose
}

So yes both fstream and sreader will be disposed.

深居我梦 2024-09-17 17:31:45

无论实例化方法是否在块内返回,using 指令都会调用 Dispose() 方法。

但请注意,您可以使用 System.IO.File.ReadAllText 方法以更少的代码实现相同的目的:

 string ReadFile(string strPath)
 {
     return System.IO.File.ReadAllText(strPath);
 }

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:

 string ReadFile(string strPath)
 {
     return System.IO.File.ReadAllText(strPath);
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文