2016-09-10 186 views
-2

我的應用程序中有輕微的內存泄漏,我想知道什麼是當我完成處理FileStream和Streamreader時的最佳做法。我應該調用Dispose後,我的文件流完成

這裏是我的代碼:

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對象而不是在被稱爲處置?或者在這裏關閉這兩個足夠好?

感謝

+0

您確定內存泄漏出現在您發佈的代碼中,您是否使用Visual Studio分析工具完成分析?,當您使用using語句時,不需要顯式調用Dispose和Close方法,請檢查此發佈有關它http://stackoverflow.com/questions/11968289/memorystream-in-using-statement-do-i-need-to-call-close –

+0

我原本以爲我的內存泄漏是由FileSystemWatcher,這顯然有一個.Net 4中的內存泄漏問題。我升級到4.5,但內存泄漏仍然發生。這真的是我的應用程序的唯一其他部分。 –

+0

Andrew Burns,請嘗試在Visual Studio中運行內存診斷以查找發生內存泄漏的代碼的確切行,請檢查這些鏈接https://blogs.msdn.microsoft.com/visualstudioalm/2014/04/02/diagnosing -memory-usage-the-new-memory-usage-tool-in-visual-studio/ https://www.youtube.com/watch?v=lU_YZtvslnI https://dzone.com/物品/分析的應用程序可視-1 –

回答

2

你並不需要調用Close()Dispose(),因爲在所有你已經包裹你流在using block

using塊將在您到達塊的末尾時自動處理您的流。

您的內存泄漏很可能存在於別處。

相關問題