Unsubscribing from de-referenced object's event?

  • Thread starter Thread starter David Veeneman
  • Start date Start date
D

David Veeneman

Do I need to unsubscribe from an object's event before I point the object
variable to a new object?

I have a method that subscribes an event handler to the ListChanged event of
a list. The list is attached to a calendar, so every time a new date is
selected, the list is recreated for the new date. The code then subscribes
the event handler to the new list. Here's the cose (m_ListForSelectedDay is
a member variable):

private void calendar_DateChanged(object sender, DateRangeEventArgs e)
{
// Initialize
DateTime newDate = e.Start;

// Get daily ist for new date
m_ListForSelectedDay = GetDailyList(newDate);

// Subscribe to ListChanged event
m_ListForSelectedDay.ListChanged += new
ListChangedEventHandler(ListForSelectedDay_ListChanged);
}

Do I need to unsubscribe from the ListChanged event before I point the
ListForSelectedDay variable to a new list? If I de-reference the object, but
I still have an event handler subscribed to it, will that keep the object
from being garbage-collected? Thanks in advance.
 
Do I need to unsubscribe from an object's event before I point the
object variable to a new object?

Most definitely. I don't think it will prevent the object from going out
of scope and being GC'ed, but until that happens you might still receive
events from it.

Let me put it this way: its easy to do, and its the right thing to do. So
do it.

-mdb
 
David Veeneman said:
Do I need to unsubscribe from an object's event before I point the object
variable to a new object?

Well, there are two issues here:

1) Getting an event from the wrong object. If you don't unsubscribe
from the event but the object raises the event, your handler will still
be called.

2) Garbage collection. The "owner" of the event keeps a reference to
the delegates in the event, which (for non-static methods) includes
keeping a reference to the "target" of the delegate. However, there's
no reference the other way. In other words, the owner of the event can
prevent the subscriber from being garbage collected, but not the other
way round.
 
I agree with ya on that.

A button keeps a reference to the form it is on, but a Form does not keep a
reference to the button.. Well.. it does.. but not from an event stand point
:-)
 
Me said:
I agree with ya on that.

A button keeps a reference to the form it is on, but a Form does not keep a
reference to the button.. Well.. it does.. but not from an event stand point
:-)

Well, the button's events keep a reference to whatever the target of
their handlers are - that needn't be a form :)
 
Back
Top