MemoryStream 对象使用using方式或者手动Dispose() ,在代码分析中引发CA2202 报错

 

以上报错。最早代码是这样

using (DESCryptoServiceProvider sa =
                new DESCryptoServiceProvider { Key = Encoding.UTF8.GetBytes(key), IV = Encoding.UTF8.GetBytes(iv) })
            {
                using (ICryptoTransform ct = sa.CreateDecryptor())
                {
                    byte[] byt = Convert.FromBase64String(encryptedValue);

                    using (var ms = new MemoryStream())
                    {
                        using (var cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
                        {
                            cs.Write(byt, 0, byt.Length);
                            cs.FlushFinalBlock();
                        }
                        //return Encoding.UTF8.GetString(ms.ToArray());
                        returnString = Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }

运行代码分析的时候,会触发“CA2202 不要多次释放对象 可以在方法 'XXXXX.DESDecrypt(string, string, string)' 中多次释放对象 'ms'。若要避免生成 System.ObjectDisposedException,不应对一个对象多次调用 Dispose。: Lines: 133 XXXXForm1.cs 133”

于是追踪,发现 微软官方说明
https://docs.microsoft.com/en-us/dotnet/api/system.io.memorystream?view=netframework-4.8
此类型实现IDisposable接口,但实际上没有任何资源可供使用。这意味着通过直接调用Dispose()或使用诸如using(在C#中)或Using(在Visual Basic中)之类的语言构造来处置它是不必要的。
也就是说,没必要释放他。

posted @ 2019-05-10 14:27  飘零_未知的坚持  阅读(835)  评论(0)    收藏  举报