我将为此创建一个新线程,因为从VS2012起,以前接受的答案不再起作用.当使用嵌套的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);
}
}
这很烦人,因为它甚至在MSDN示例中也列出了.Microsoft甚至已针对此警告提供了建议的修复程序,但不再修复该警告.根据您使用的Visual Studio版本/编译器,这可能对您不起作用.
可以通过对代码进行以下更改来正确修复以上代码:
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();
}
除了代码不易读之外,这是解决方案.看来他们最近改变了代码分析,并且如前所述,不需要第二个内部try / finally块.我不明白为什么.以前的修复应该足以在发生异常的情况下处理MemoryStream对象.
我仍然认为CA2202异常是虚假的,正确的解决方案是忽略警告-底层对象不应处置其不拥有的引用.这仅用于讨论和参考.
I'm going to create a new thread for this as previous accepted answers no longer work as of VS2012 and up. 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 (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. Microsoft even has a recommended fix for this warning, however it no longer fixes the warning. This may or may not work for you, depending on what Visual Studio version/compiler you are using.
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. 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.
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. This is merely here for discussion and reference.
本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文