简体   繁体   中英

Why does Bitmap cause rule CA2000, but Image does not?

There are a lot of questions on SO lamenting the fact that Code Analysis rule CA2000 is being applied possibly too rigorously by VS2010, but I seem to have run into a case where it should be applied, but isn't.

Consider the following code:

Image srcImage = Image.FromFile(source);
Bitmap newImage = new Bitmap(newWidth, newHeight);

using (Graphics gr = Graphics.FromImage(newImage))
{
    gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
newImage.Save(destination, ImageFormat.Jpeg);

Now if I run Code Analysis in Visual Studio 2010 on this, it will complain about newImage not being disposed (easy fix, put it in another using block), but it doesn't complain about srcImage (which also has a Dispose() method that I'm never calling). Does anyone know why Code Analysis doesn't complain here?

CA2000 and the similar/related CA2213 (DisposableFieldsShouldBeDisposed) and CA1001 (TypesThatOwnDisposableFieldsShouldBeDisposable) rules are rather strict about how they recognize "ownership" of a disposable. They will only consider your code to be the owner of a disposable instance if an instance constructor is used to create the instance directly in your code. Since you use Image.FromFile to create the instance for srcImage, the rule doesn't recognize your code as the owner.

If you disagree with this rule behaviour, you may want to create a bug report at https://connect.microsoft.com/visualstudio/feedback . (If you care about the disposable field rules, you might want to vote for the existing https://connect.microsoft.com/VisualStudio/feedback/details/485291/typesthatowndisposablefieldsshouldbedisposable-rule-ca1001-is-too-permissive suggestion while you're at it.)

Well it should "complain about srcImage" too, however I guess that it doesn't complain about it because you are passing it to the DrawImage method " gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight)); ", So either it is not smart enough to know that it will not being used for more actions after the method returned, or maybe it assumed that you used it in gr instance that will be disposed. Anyway you should use using for srcImage just like what you are doing with newImage and don't follow the Code Analysis on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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