1

I am working on an application where i am creating dynamic controls in a tablelayoutpanel, that includes two picture box and 3 combobox, each picturebox creates 2 GDI objects and each combobox creates 1, leading to the creation of 7 GDI objects in a row. But when my work is done I am trying to dispose the controls of tablelayoutpanel, but GDI objects are not getting disposed , leading to application crash. Everytime i open that tablelayoutpanel it appends the GDI objects to the previous count. After a point of time, it crosses 10,000 and application stops responding. I am trying something like this to dispose the GDI objects

for(int i =TableLayoutPanel.Controls.count -1;i >=0;--i )
{
TableLayoutPanel.Controls[i].Dispose();
}

this deletes some GDI objects but not most of them. can anybody help me out with this.Also when i close the form(not the entire application),still GDI objects are not getting disposed.

SHASHA
  • 90
  • 1
  • 12
  • 3
    GDI objects are things like Pens and Brushes. Controls are just controls. Before you dispose of them you probably need to remove them from the collection and make sure nothing else references them – Ňɏssa Pøngjǣrdenlarp Jul 14 '18 at 14:30
  • 1
    Show the nature of the GDI objects you're referring to and how/when they are creted. – Jimi Jul 14 '18 at 14:31
  • Golden rule is to *never* store "GDI objects". They are very cheap to create (a microsecond) but very expensive to store. So you create them when you need them, always with *using*. If that is inconvenient for some unseen reason then you do have to add the Dispose() calls to your code, same place where you dispose the controls. – Hans Passant Jul 14 '18 at 17:02
  • 2
    You might want to fret a bit about the reason why the garbage collector never seems to run. It is not entirely unusual in a program that just doesn't manipulate a lot of data, making Dispose() calls so important, but a deadlocked finalizer thread can happen. Which is very, very bad. It is tricky to debug without using a memory profiler. A simple test you can do is use a Timer in your main form and have its Tick event handler call GC.Collect(). With the expectation that you now no longer have this problem. – Hans Passant Jul 14 '18 at 18:32

1 Answers1

0

As suggested by @hans calling Gc.collect() worked

SHASHA
  • 90
  • 1
  • 12
  • 1
    It was *meant* to be a test. Test succeeded, you don't have a deadlocked finalizer thread and merely a problem with the GC not running often enough. If you keep then then make sure you don't make the Interval too small. Avoid going below a minute (60000). – Hans Passant Jul 15 '18 at 12:44