我有如下代码
public static byte[] Compress(byte[] CompressMe)
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gz = new GZipStream(ms, CompressionMode.Compress,true))
{
gz.Write(CompressMe, 0, CompressMe.Length);
ms.Position = 0;
byte[] Result = new byte[ms.Length];
ms.Read(Result, 0, (int)ms.Length);
return Result;
}
}
}
这段代码可以正常运行,但当我对其进行代码分析时,会出现以下消息
CA2202 : Microsoft.Usage : Object 'ms' can be disposed more than once in
method 'Compression.Compress(byte[])'. To avoid generating a
System.ObjectDisposedException you should not call Dispose more than one
time on an object.
就我个人而言,当GZipStream被Dispose掉时,由于构造函数的最后一个参数(leaveOpen=true),它将保留底层流(ms)的打开状态。
如果我稍微更改我的代码... 移除对MemoryStream的'using'块,并把'leaveOpen'参数改为false...
public static byte[] Compress(byte[] CompressMe)
{
MemoryStream ms = new MemoryStream();
using (GZipStream gz = new GZipStream(ms, CompressionMode.Compress, false))
{
gz.Write(CompressMe, 0, CompressMe.Length);
ms.Position = 0;
byte[] Result = new byte[ms.Length];
ms.Read(Result, 0, (int)ms.Length);
return Result;
}
}
然后会出现...
CA2000 : Microsoft.Reliability : In method 'Compression.Compress(byte[])',
object 'ms' is not disposed along all exception paths. Call
System.IDisposable.Dispose on object 'ms' before all references to
it are out of scope.
我赢不了..(除非我漏看了什么)我尝试了各种方法,例如在代码块中添加try/finally,并在其中Dispose MemoryStream,但要么说我正在两次处理它,要么根本没有处理!!