This is a C# WinForm question. I have a MDI child form, when the form is opened, it will generate many tables to display in a DataGridView. The tables can be big and I use DataBinding to connect the tables to the DataGridView. When I close the form, I notice that the memory taken by the form is reclaimed timely.
I use the normal way of showing the MDI child form as:
var f = new FormBigMemory(objPassedIn);
f.Show();
As shown here, I cannot explicitly call the Dispose() method of the form. I assume that when f is out of its life circle, .net will automatically reclaim the memory it takes.
Since the form takes a lot memory, I want to explicitly call GC.Collect(); (I know it may not be a good idea to do so). In order to do this, I change the code to show the form in dialog model using the following code:
using(var f = new FormBigMemoryDialog(objPassedIn);
{
f.ShowDialog();
}
GC.Collect();
I am very disappointed to see that the memory taken by the form isn't reclaimed after GC.Collect() is called. I use memory profiler tool to get the snapshot of the memory after the form is closed and GC.Collect() is called. The biggest memory is held up by a BindingList! I really don't understand: if the whole form is disposed, why the BindingList still exists in the memory. I have checked my code and there is no where the BindingList reference is leaked out of the form.
Any idea why this wired thing happens to me? Many thanks to any suggestion and tips on .net memory management.
Edit:
Thanks for many answers. Let me clear some points.
I don't mean to dispose the BindingList. A BindingList is used as an array in my code so I would expect to see the reclaim of the memory held by the BindingList. My bad not to say clearly.
I understand not to call the GC action myself. But in my case, I want to explicitly see the reclaim of memory held up by the form immediately after the form is closed, anyway to do that? Example code?
In my problem, I can repeatedly open the same form multiple times and each time I close the form, the memory consumption increases, until the OutOfMemory throws. This is obviously not right. What I expect to see is, after the form is closed, the memory drops back to the original level and I can repeatedly open the form and close it without increasing the memory (dramatically).
Edit 2:
I further investigated the code. The biggest array (a BindingList) is not released after the form is closed. It is referred by a BindingSource and the BindingSource is referred by EventHandler, CurrencyManager, and a user control. The BindingSource and the user control are both referred by the (closed) form and the (closed) form is referred by some event handlers.
The above is the memory snapshot after I closed the form. I use dialog model to open the form and after it is closed, its Dispose() method is called and after that I also call GC.Collect() to force the memory to be reclaimed. Why after this the form instance still exists in my memory snapshot??