Re: Unit testing event handlers

Tech-Archive recommends: Fix windows errors by optimizing your registry



On Nov 27, 3:36 pm, "David Veeneman" <dav...@xxxxxxxxxx> wrote:
Nope--the garbage collector won't collect it if you haven't unsubscribed.

Yes, it will.

Ask the Princeton team for the DARPA Grand Challenge:

http://www.codeproject.com/showcase/IfOnlyWedUsedANTSProfiler.asp

Yes, you can get garbage collection issues if you don't unsubscribe
from events - but not the way you're suggesting.

A memory leak of this exact type torpedoed their entry in DARPA's $2 million
Grand Challenge. So, yes, you do have to unsubscribe.

No, you don't.

You need to understand which way the references work. A delegate
instance holds a reference to its target - the object it will call the
method on.

Suppose you have a form, and some random expensive object subscribes
to the Click event of a button on that form: the random expensive
object won't be eligible for garbage collection until either the form
itself is eligible for garbage collection, or the event handler is
unsubscribed - the form effectively has a reference to the object. The
reverse is *not* true, however: the form can become eligible for
garbage collection *without* the random expensive object becoming
eligible.

So to cut it short: no, in the unit test example you gave, you do
*not* need to unsubscribe.

Jon
.


Quantcast