General event subscription question

Posts   
 
    
Sam avatar
Sam
User
Posts: 95
Joined: 30-Jun-2004
# Posted on: 14-May-2006 00:43:37   

This question is not necessarily specific to LLBLGen but I thought I might try to get an answer here. I have a reference to a customer object and want to open up the details window for editing in a modal dialog (winforms app). I am also interested in if a certain property is changed so in the OnLoad event I subscribe the the PropertyIAmInterestedIn.Changed event. I then bind this object to the form. Now if I close the modal dialog and reopen it the event is resubscribed to and will fire twice; open it three and get the event firing 2 times (no good). I have tried unsuperscribing (-=) to the event before subscribing in hopes of cleaning up any prior subscription but to no avail. I know that this is basic programming but I would not embarrass myself by asking if I was not at my wits end.

Thanks in advance.

sparmar2000 avatar
Posts: 341
Joined: 30-Nov-2003
# Posted on: 14-May-2006 04:55:51   

can you post a sample code?

Sam avatar
Sam
User
Posts: 95
Joined: 30-Jun-2004
# Posted on: 15-May-2006 04:02:32   

I am using the Composite UI application block with a model view presenter architecture. When I set the reference to the view in my presenter I wire up my Changed events like such:


m_View.SalesSubject.StateCodeChanged += new EventHandler(SalesSubject_StateCodeChanged);

this code is called each time that the dialog is created and displayed. Unfortuantely as stated before the number of times the event is called for a particular SalesSubject (cusotmer) = the number of times that specific SalesSubject has been open. Basically I want to subsribe the the event once. I tried this code:


m_View.SalesSubject.StateCodeChanged -= new EventHandler(SalesSubject_StateCodeChanged);
m_View.SalesSubject.StateCodeChanged += new EventHandler(SalesSubject_StateCodeChanged);

Hoping that it would delete the event subscription if it existed. No dice. I hope this makes senses.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39928
Joined: 17-Aug-2003
# Posted on: 15-May-2006 21:38:54   

You've to remove the events in the Closing event handler of the form. This is indeed rather weird, but necessary, as an eventhandler bound in class X to event of class Y will stick as it really means that Y points to X.EventHandlerMethod, which thus means that X also isn't going to be garbage collected. X is the form here, Y the entity.

So rule of thumb: if the object which exposes the events is kept after the object which binds to the events is closed/dismissed, you have to clean up the event handlers manually. I do that too in the designer editor windows for example: editor opens: events get bound. editor closes, events are cleaned up.

Frans Bouma | Lead developer LLBLGen Pro