CA2202: Do not dispose objects multiple times

你离开我真会死。 提交于 2019-12-01 08:32:04

问题


I have a class like so...

public class Class1
{
    public Class1()
    {
        byte[] plainText = new byte[1024];
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                csEncrypt.Write(plainText, 0, plainText.Length);
                csEncrypt.FlushFinalBlock();
                csEncrypt.Flush();
                encrypted = msEncrypt.ToArray();
            }
        }
    }
    public ICryptoTransform encryptor { get; set; }
    public byte[] encrypted { get; set; }
}

Code analysis throws the following warning. Do not dispose objects multiple times.

http://msdn.microsoft.com/en-us/library/ms182334.aspx.

I am not able to comprehend this line in the article above [Example section]... "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."


回答1:


It states that when you call Dispose on a resource, it will dispose all the resource which it holds. So the inner resource here csEncrypt which holds the outer resource msEncrypt on csEncrypt.Dispose it will have disposed msEncrypt as well.

Later msEncrypt.Disopse is called, so Code Analysis warns you about calling Dispose multiple times.



来源:https://stackoverflow.com/questions/22244247/ca2202-do-not-dispose-objects-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!