Event subscription

  • Thread starter Thread starter joe
  • Start date Start date
J

joe

Hi,

I have a user control which subscribes to user defined
events fired from a worker thread.
I have a variable, which holds reference of an instance of
this control:

MyClass
{
MyControl m_MyControl;
......
SomeFunction()
{
m_MyControl=new MyControl();
}
}



From time to time I call this function to assign a new
control to m_MyControl and I hope that the old control
will be garbage-collected. But I found that even if I
assign a new instance to m_MyControl, I still get events
received by the control previously assigned to
m_MyControl, which means that the it (the old control) is
still alive . Does that mean that as long as a control (or
any object for that matter) has subscribed but no
unsubscribed for an event it is deemed alive and cant be
GC? They say in the books that unsubscribing is rarely
necessary?

Thanks,
joe
 
Unsubscribing is not necesarry if the entire application
terminates, but if you instantiate classes and subscribe
to their events dynamically many times during the life
time of the application you should always unsubscribe
from the events. There is an internal counter that is
increased everytime somebody subscribes to an event and,
as far as I know, the garbage collector will never
collect the object until all the counters are 0...
I read about this in "Professional C#" from wrox, I
believe...
 
So its possible to leak on events ?

So if an object subscribes to an event then that object is destroyed, what
happens to the invokation list? Is that cleaned up?
 
I followed Bob Powel's advice (thanks)
and I called MyUserControl.Dispose(). But I still get
events trapped by the just disposed control unless I
unsubscribe in the MyControl_Disposed event handler.
As for the internal counter that the anonymous participant
suggests, which object cant be GC, the one that generates
events or the recipient? In my case it is the recipient
that lingers even after Dispose. Why should it be alive
after I called Dispose, even if it is still subscribed for
some event(s).

joe
 
Back
Top