c# - 如何解决CA2202 :To avoid generating a System. ObjectDisposeException警告

标签 c# file json.net warnings

每次在 Visual Studio 2015 上运行 Code Analysis 时,有一些烦人的警告。所有这些都在这样的方法中:

这是我的方法:

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);
    }

}

那么为什么会出现这个警告呢?怎么解决呢?最重要的是 我的错误在这个方法中,在我看来非常完美

警告说明

Severity Code Description Project File Line Warning CA2202 : Microsoft.Usage : Object 'file' can be disposed more than once in method 'JsonHelper.ReadJson(string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

最佳答案

MSDN:

Nested using statements (Using in Visual Basic) can cause violations of the CA2202 warning. If the IDisposable resource of the nested inner using statement contains the resource of the outer using statement, the Dispose method of the nested resource releases the contained resource. When this situation occurs, the Dispose method of the outer using statement attempts to dispose its resource for a second time.

问题:

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"

解决方案:

你需要这样做(当一切顺利时在finally block 中处理对象,或者在发生错误时在catch block 中处理对象):

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();
    }
}

关于c# - 如何解决CA2202 :To avoid generating a System. ObjectDisposeException警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34469841/

相关文章:

c# - 在 C# 中动态覆盖任何方法

c# - 我如何创建一个流畅的 Nhibernate 映射,该映射具有多个表的连接但仅从每个表中选择选择性列?

c# - 我如何在 ASP.NET 中使用带有图标和格式的 JQuery Datepicker

python - 如何检查 python cv2.imwrite 是否正常工作

c - 从文件 c 读取输入时出错

c# - 有没有办法在不使用 JsonIgnore 属性的情况下忽略 Json.NET 中的 get-only 属性?

c# - 双向链表到 JSON

c# - nant <version> 任务

c# - 如何在 WinRT 的应用 ViewModel 中异步使用 json.net?

php - php 中的字符串到压缩流