【发布时间】:2023-04-01 13:00:02
【问题描述】:
我的应用程序有轻微的内存泄漏,我想知道当我处理完 FileStream 和 Streamreader 后,最佳做法是什么。
这是我的代码:
using (var stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(stream))
{
//do what I need with the file
sr.Close();
stream.Close();
}
我应该在流对象和 StreamReader 对象上调用 Dispose 吗?或者在这里关闭两者是否足够好?
谢谢
【问题讨论】:
-
您确定您发布的代码中存在内存泄漏,您是否使用 Visual Studio 分析工具进行了分析?,您在使用时不需要显式调用 Dispose 和 Close 方法using 声明,查看这篇关于它的帖子stackoverflow.com/questions/11968289/…
-
我最初认为我的内存泄漏是由 FileSystemWatcher 引起的,它在 .Net 4 中显然存在内存泄漏问题。我升级到 4.5 但仍然发生内存泄漏。这确实是我的应用程序的唯一其他部分。
-
Andrew Burns,请尝试在 Visual Studio 中运行内存诊断以找到发生内存泄漏的确切代码行检查这些链接blogs.msdn.microsoft.com/visualstudioalm/2014/04/02/…youtube.com/watch?v=lU_YZtvslnIdzone.com/articles/profiling-application-visual-1
标签: c# memory-leaks filestream