WinForms, Events, and Subscribers


D

Doug Perkes

Background
--------------------------
I am in the process of creating a WinForms app with many forms.

I have a set of forms that all subscribe to events on a custom object.

When the forms are created I manually create a subscription in the
form to one or more events in the custom object. (BTW, this is the
same design pattern used by IssueVision discussed at DevDays).

I have a controller form (MDI parent) that determines which child form
is currently being viewed. When a new child form is selected, the
current child form is manually closed [using Form.Close()] and
disposed [using Form.Dispose()] and then the new form is shown. This
keeps only one child form open at a time.

Question
--------------------------
Even after child forms are closed and disposed, when events are raised
from the custom object, the events are still triggered in the disposed
child forms.

Could someone explain why this is happenning? I must be
misunderstanding something. Do the child forms need to manually
unsubscribe from the events in the Closing event? Is there a better
place to do this?

TIA,

Doug
 
Ad

Advertisements

S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Dough,

Disposing a form means that you destroy the underlaying windows control
(Handle) this doesn't mean that the .NET form object is destroyed. It's
going to be alive until there are no references to the object. However
because the form is disposed when one use its members an exception might be
thrown. When you subscribe for an event the event (source object) actually
keeps a reference to the form. Thus, the .NET object will be alive as long
as the event source is alive and will receive any event it fires.

That's why when you close the form you have to unhook the events. Good place
for this is in responce to Form.Closed event
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top