I have an application where I use a custom button. For this I use separate drawing class for the drawing. The drawing class was derived from IDisposable and I have invoked GC.SuppressFinalize(this) in its interface. Everything works fine, but when I import an image for button, the dispose is invoked which disposes my image which is leading to an Invalid exception.
We are using GC.SuppressFinalize(this) for disposing the managed resources used in our application and I found this is causing the issue.
This is a simple code for replication.
public class Custom : Control
{
private DrawingClass drawingClass;
public Custom()
{
this.drawingClass = new DrawingClass();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(Image != null)
e.Graphics.DrawImage(Image, this.ClientRectangle.Location);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
Image.Dispose();
}
}
public Image Image { get; set; }
}
public class DrawingClass : IDisposable
{
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
When I drag and drop this Custom
control and try to assign an image using Import process, the dispose was invoked which disposes the Image which leading exception when drawing.
The Dispose was invoked from " System.Windows.Forms.UnsafeNativeMethod ".
Can someone suggest what is wrong or using GC.SuppressFinalize() does really cause problems ?