2015-12-26 73 views
1

每次在visual studio 2015,當我運行Code Analysis時,有一些惱人的警告。所有這些都是在這樣的方法:如何解決CA2202:爲了避免生成一個System.ObjectDisposedException警告

這裏是我的方法:

public static JObject ReadJson(string file_path) 
{ 
    try { 
     JObject o1 = JObject.Parse(File.ReadAllText(file_path)); 
     using (StreamReader file = File.OpenText(file_path)) 
     { 
      using (JsonTextReader reader = new JsonTextReader(file)) 
      { 
       return (JObject)JToken.ReadFrom(reader);//the warning is here 
      } 
     } 
    } 
    catch 
    { 
     return default(JObject); 
    } 

} 

那麼,爲什麼這個警告出現?如何解決它?而最重要的是什麼 我在這個方法的錯,在我看來很完美

警告說明

嚴重性代碼說明項目文件行警告CA2202: Microsoft.Usage:對象「文件」可以在 方法'JsonHelper.ReadJson(string)'中多次處理。爲避免生成一個 System.ObjectDisposedException,您不應該在對象上調用Dispose超過 一次。

+0

我使用 '使用Newtonsoft.Json; 使用Newtonsoft.Json.Linq;' –

回答

2

MSDN:

嵌套using語句(使用Visual Basic中)可能會導致侵犯CA2202警告 。如果嵌套內部使用語句的IDisposable資源包含外部使用語句的資源 嵌套資源的Dispose方法將釋放所包含的 資源。發生這種情況時,外部使用語句的Dispose方法會嘗試第二次處理其資源。

問題:

using (StreamReader file = File.OpenText(file_path)) 
{ 
    using (JsonTextReader reader = new JsonTextReader(file)) 
    { 
     return (JObject)JToken.ReadFrom(reader);//the warning is here 
    } //"file" will be disposed here for first time when "reader" releases it 
} //and here it will be disposed for the second time and will throw "ObjectDisposedException" 

解決方案:

你需要做的是這樣的(配置對象在最後塊時一切正常,或在catch塊當發生錯誤時):

public static JObject ReadJson(string file_path) 
{ 
    StreamReader file = null; 
    try { 
     JObject o1 = JObject.Parse(File.ReadAllText(file_path)); 
     file = File.OpenText(file_path); 
     using (JsonTextReader reader = new JsonTextReader(file)) 
     { 
      return (JObject)JToken.ReadFrom(reader); 
     } 
    } 
    catch 
    { 
     return default(JObject); 
    } 
    //dispose "file" when exiting the method 
    finally 
    { 
     if(file != null) 
      file.Dispose(); 
    } 
} 
+0

我認爲你需要刪除從捕獲配置,或者你也會在這裏雙重處置... –

+0

@ Clockwork-Muse Yup!感謝指點。 – Shaharyar