Reputation: 69
I have a dotnet application that i see it growing all time in terms of memory, than I decide to do some tests, starting by this code
Form f0 =null;
using(Form f1 = new Form())
{
f0=f1;
f0.Text="Hellow!";
f0.ShowDialog();
}
f0.Text="Hellow, you here me";// exception attempt here but nothing happens.
that was my first question.
the second:
when i have Control like DataGridView
inside Form (and created in this form) marked by default as private; suppose i changed it to be public, i wante initialize Columns from external(from Form) Helpers, does it change the way of garbage collector?
Upvotes: 0
Views: 111
Reputation: 4037
part1:
f0=f1;
means that you have kept reference to the form object.
Form.Dispose
(that is called in the end of using
block) does not destroy the form object completely. It release certain unmanaged resources (like window and control handles, etc) however runtime objects (like Form
) are still alive in the memory.
Those objects are marked as ready to be garbage collected
but GC does not destroy them immediately.
That is why f0.Text="Hellow, you here me"
operator works without null reference exception after using
.
However f0.Show()
after using
will fail with object disposed exception
part 2: GC calculates object references so helpers you are using should not break GC until they are keeping references on instances
class Helper
{
public void AddColumn(Grid grid, string name)
{
grid.Columns.Add(new GridColumn(name));
}
}
this does not store reference on grid or gridcolumn instance so GC is not affected
Upvotes: 1
Reputation: 18013
Disposing an object does not mean it will be suddenly inaccessible in terms of garbage collection. Until you keep a reference to such an object it will be tracked by the GC.
So even though your form is disposed at the end of the using
block, you can still access it via the f0
reference you assigned. It seems, you can set some public properties of a disposed Form
but try f0.ShowDialog
outside of the using
block and you will get an ObjectDisposedException
.
As for the 2nd question: Without any code it is hard to say anything. But try not to mix multiple questions in one post. A generic answer to your generic question: do not keep any references from the helper class to the created instances and you will be alright.
Upvotes: 2