ImageList: removing the original image removes it from the list

ImageList should create a copy of all the images inserted into it. Therefore, after adding them to the list, it should be safe to place the originals.

Why does the test fail below?

Bitmap test = new Bitmap(128, 128); ImageList il = new ImageList(); il.Images.Add(test); Assert.AreEqual(1, il.Images.Count); // OK, image has been inserted test.Dispose(); // now let dispose the original try { var retrievalTest = il.Images[0]; } catch (ArgumentException) // ... but this Exception happens! { } Assert.AreEqual(1, il.Images.Count); // and this will fail 

What happens here is this: when trying to get an image, ImageList discovers that the original has been deleted, and removes it from ImageList.

Why is this happening, I thought ImageList should create a copy of the image?

+3
source share
2 answers

Yes, ImageList creates a copy of the bitmap. But your test code works with the famous lazy initialization scheme, which is so common in the .NET framework. It is important when creating a copy. This only happens when necessary. Make small changes to your code to hurry up:

 il.Images.Add(test); var dummy = il.Handle; // <== NOTE: added test.Dispose(); // no problem 

And you will see that recycling is no longer a problem.

Not sure how to give the right advice here, the code is too synthetic. This works pretty well overall, ImageList makes a copy when its consumers start using their bitmap, Treeview or ListView. In general, avoid using ImageList as a collection object; it was not created to do the job. Separate the view from the model and you will be left without any problems.

+5
source

ImageList should create a copy of all the images that are inserted into it.

I do not see any indication in the documentation that it does. So the simple answer is: your guess is wrong.

+1
source

Source: https://habr.com/ru/post/1399167/


All Articles