We're using a System.Windows. Forms.ImageList to store a bunch of Images that
I've loaded, and rendering each image in the ImageList during a draw loop.
The process was running unusually slow and was causing memory spikes. After
several hours we discovered that the ImageList.Image s indexer is actually
returning a copy of the added Images instead of simply returning a reference.
Needless to say, we were a bit surprised and disturbed to discover this.
1) Can anyone answer why the ImageList collection returns a copy instead of
a reference?
2) Is there a way to get the reference instead of a copy?
If you run the example code below, the output to the console window will be
"Different Image".
// Example Code
System.Windows. Forms.ImageList imageList =
new System.Windows. Forms.ImageList ();
System.Drawing. Image image =
System.Drawing. Image.FromFile( @"C:\image.png" );
imageList.Image s.Add(image);
// Get the same Image twice!
System.Drawing. Image imageFromList1 = imageList.Image s[0];
System.Drawing. Image imageFromList2 = imageList.Image s[0];
if (object.Referen ceEquals(imageF romList1, imageFromList2) )
{
Console.WriteLi ne("Same Image");
}
else
{
Console.WriteLi ne("Different Image");
}
Console.ReadLin e();
I've loaded, and rendering each image in the ImageList during a draw loop.
The process was running unusually slow and was causing memory spikes. After
several hours we discovered that the ImageList.Image s indexer is actually
returning a copy of the added Images instead of simply returning a reference.
Needless to say, we were a bit surprised and disturbed to discover this.
1) Can anyone answer why the ImageList collection returns a copy instead of
a reference?
2) Is there a way to get the reference instead of a copy?
If you run the example code below, the output to the console window will be
"Different Image".
// Example Code
System.Windows. Forms.ImageList imageList =
new System.Windows. Forms.ImageList ();
System.Drawing. Image image =
System.Drawing. Image.FromFile( @"C:\image.png" );
imageList.Image s.Add(image);
// Get the same Image twice!
System.Drawing. Image imageFromList1 = imageList.Image s[0];
System.Drawing. Image imageFromList2 = imageList.Image s[0];
if (object.Referen ceEquals(imageF romList1, imageFromList2) )
{
Console.WriteLi ne("Same Image");
}
else
{
Console.WriteLi ne("Different Image");
}
Console.ReadLin e();
Comment