zobie
Tue Oct 19 11:18:47 CDT 2004
Thanks for your help... this is extremely helpful information.
- Nate
Andreas Suurkuusk wrote:
> Hi,
>
> You're right. There's a memory leaks when removing owned forms, however it
> will in many cases not keep more than one Form referenced. In your example,
> if you click the button repeatedly, you still only have one live instance of
> Form2.
>
> The error is the way the form is removed in RemoveOwnedForm:
>
> The following code is used to remove the form (indexForm is the index of the
> form to remove):
>
> Array.Copy( formArray, indexForm+1, formArray, indexForm, nForms -
> indexForm-1);
>
> What's missing is code to null the leftover instance at the end of the
> array:
>
> formArray[nForms-1] = null;
>
> How bad the memory leak is depends on how many child forms a form is the
> owner of, and the order they are removed from the owner. The code below will
> cause 10 Form2 instances to become wrongly referenced by the owner (if you
> reverse the Close loop, only one instance will be leftover):
>
> private void button1_Click(object sender, System.EventArgs e)
> {
> Form2[] forms = new Form2[10];
> for( int i=0; i < forms.Length; i++ )
> {
> forms[i] = new Form2();
> forms[i].Owner = this;
> forms[i].Show();
> }
>
> for( int i=forms.Length; --i >= 0; )
> {
> forms[i].Close();
> }
> }
>
> Note that calling Close() on the form will Dispose it, and it will be
> automatically removed from the owner. There's no need to set the Form2
> references to null, since the variable will go out of scope when the method
> returns.
>
> I have not checked whether this leak still exists under Whidbey, but
> hopefully
> it has been fixed.
>
> Best regards,
>
> Andreas Suurkuusk
> SciTech Software AB
>
>
>
> "zobie" <zobie@zobie.com> skrev i meddelandet
> news:417438AF.8070502@zobie.com...
>
>>I have created a project that has two forms. Form1 has a button which runs
>>the following code:
>>
>>private void button1_Click(object sender, System.EventArgs e)
>>{
>>Form2 f = new Form2();
>>f.Owner = this;
>>f.Show();
>>f.Close();
>>this.RemoveOwnedForm(f);
>>f.Dispose();
>>f = null;
>>}
>>
>>Using .NET Memory Profiler (
http://www.scitech.se/memprofiler) I am able
>>to see that Form2 is not disposed. This seems to be a huge issue. Has
>>anyone experienced this problem? Is there a workaround? Have I done
>>something incorrectly?
>>
>>If I remove the line where the Owner is set, there is no problem with
>>Form2 being Disposed.
>>
>>Thanks,
>>Nate
>
>
>
>
>
>