2017-10-06 75 views
0

剛跑代碼分析我繼承的一個應用程序,並提出了類似下面的代碼警告:代碼分析警告有關對象廢棄的潛在兩次

using (StreamWriter tw = File.AppendText("Log.txt")) 
{ 
    try 
    { 
     tw.WriteLine(DateTime.Now.ToString("------------------------"); 
     tw.WriteLine(data); 
    } 
    catch(Exception ex) 
    { 
     Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "Error writing to the log file: {0}", ex.Message)); 
    } 
    finally 
    { 
     tw.Close(); 
    } 
} 

如果我註釋掉finally塊,則不會引發警告。我的印象是關閉一個流編寫器只關閉底層文件,但實際上並沒有處理編寫器對象。代碼分析是否被破解,或者我誤解了應該如何使用流編寫器?

在此處,代碼分析抱怨兩個作家的可能的部署和底層流兩次又如:

using (TextReader tr = new StreamReader(File.OpenRead(filename))) 
{ 
    while (tr.ReadLine() != null) 
    { 
     counter++; 
    } 

    tr.Close(); 
} 

它抱怨都trFile.OpenRead(filename)

+0

'using'自動處理創建的實例,您不必顯式調用'.Close()'或'.Dispose()'。我建議谷歌搜索,如何使用'工作 –

+0

是的,'關閉'調用'處置'。這是一個奇怪的API。 – Blorgbeard

+3

@o_O問題作者表示他們認爲「Close」與處置不同,並不是「使用」不處理對象。 – Servy

回答

2

Close just calls Dispose on the object,所以是的,你處置的對象兩次。 (不是兩次處理對象是有問題的,只是多餘的。)

+0

是的,我錯過了那部分。一致性,微軟?首先,他們希望我們在'使用'中包裝'IDisposable',然後這個。 – ajeh

相關問題