2015-12-26 58 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