简体   繁体   English

Visual Studio Code Analysis中的可怕的CA2202警告

[英]The dreaded CA2202 warning in Visual Studio Code Analysis

I'm going to create a new thread for this as previous accepted answers no longer work as of VS2012 and up. 我将为此创建一个新线程,因为从VS2012起,以前接受的答案不再起作用。 When using nested using statements, Visual Studio code analysis gives you the annoying CA2202 Do not dispose objects multiple times, for the following code: 当使用嵌套的using语句时,对于以下代码,Visual Studio代码分析使您烦恼的CA2202不要多次处置对象:

using (MemoryStream msData = new MemoryStream(encodedData))
            {
                using (BinaryWriter wtr = new BinaryWriter(msData))
                {
                    wtr.Write(IV, 0, IV.Length);
                    wtr.Write(encrypted, 0, encrypted.Length);
                }
            }

This is annoying, because it is even listed in MSDN samples . 这很烦人,因为它甚至在MSDN示例中也列出了。 Microsoft even has a recommended fix for this warning, however it no longer fixes the warning. Microsoft甚至已针对此警告提供了建议的修复程序 ,但不再修复该警告。 This may or may not work for you, depending on what Visual Studio version/compiler you are using. 根据您使用的Visual Studio版本/编译器,这可能对您不起作用。

The above code can be fixed, properly, with the following change to the code: 可以通过对代码进行以下更改来正确修复以上代码:

MemoryStream msData = null;
try
{
    msData = new MemoryStream(encodedData);
    try
    {
        using (BinaryWriter wtr = new BinaryWriter(msData))
        {
            wtr.Write(IV, 0, IV.Length);
            wtr.Write(encrypted, 0, encrypted.Length);
        }
    }
    finally
    {
        msData = null;
    }
}
finally
{
    if (msData != null)
        msData.Dispose();
}

Aside from the code being much less readable, this is the solution. 除了代码不易读之外,这是解决方案。 It would appear that recently they changed code analysis and as previously mentioned did not require the second inner try/finally block. 看来他们最近改变了代码分析,并且如前所述 ,不需要第二个内部try / finally块。 I don't understand why, however. 我不明白为什么。 The previous fixes should have been enough to deal with disposing the MemoryStream object in the event of an exception. 以前的修复应该足以在发生异常的情况下处理MemoryStream对象。

I still think the CA2202 exception is bogus and the proper solution is to ignore the warning - underlying objects should not be disposing of references it does not own. 我仍然认为CA2202异常是虚假的,正确的解决方案是忽略警告-底层对象不应处置其不拥有的引用。 This is merely here for discussion and reference. 这仅用于讨论和参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM