delegate instance and target (C# in depth)

P

puzzlecracker

A cut-and-paste from the Jon's book, with a question to follow:

Utter garbage! (Or not, as the case may be…)—It’s worth being aware
that a
delegate instance will prevent its target from being garbage
collected, if
the delegate instance itself can’t be collected. This can result in
apparent
memory leaks, particularly when a “short-lived” object subscribes to
an event in a “long-lived” object, using itself as the target. The
long-lived
object indirectly holds a reference to the short-lived one, prolonging
its lifetime

1) what does target refer to (delegate instance will prevent its
target from being garbage)?
 
I

Ignacio Machin ( .NET/ C# MVP )

A cut-and-paste from the Jon's book, with a question to follow:

Utter garbage! (Or not, as the case may be…)—It’s worth being aware
that a
delegate instance will prevent its target from being garbage
collected, if
the delegate instance itself can’t be collected. This can result in
apparent
memory leaks, particularly when a “short-lived” object subscribes to
an event in a “long-lived” object, using itself as the target. The
long-lived
object indirectly holds a reference to the short-lived one, prolonging
its lifetime

1) what does target refer to (delegate instance will prevent its
target from being garbage)?

The delegate is like a definition , but the concrete method being
called belong to an instance of a given type. The target is that
instance.

Now a good question is what happen if the target is a static method.
In this case the above should not apply.
 
J

Jon Skeet [C# MVP]

puzzlecracker said:
A cut-and-paste from the Jon's book, with a question to follow:

Utter garbage! (Or not, as the case may be=3F)=3FIt=3Fs worth being aware
that a
delegate instance will prevent its target from being garbage
collected, if
the delegate instance itself can=3Ft be collected. This can result in
apparent
memory leaks, particularly when a =3Fshort-lived=3F object subscribes to
an event in a =3Flong-lived=3F object, using itself as the target. The
long-lived
object indirectly holds a reference to the short-lived one, prolonging
its lifetime

1) what does target refer to (delegate instance will prevent its
target from being garbage)?

The instance (or rather, the reference to the instance) that the action
will be called on. It's defined in the previous paragraph :)

So for example, if I do:

EventHandler x = someObject.SaveDocument;

then the value of "someObject" is the target. When the delegate is
invoked, it's like calling someObject.SaveDocument().
 

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