Aleksey said:
Hi all!
It's a theoretical question.
Suppose I have object A with event OnAction and I have object B that
connects to this event.
I create object B as a local method variable and in this method I connect
object B to OnAction of object A.
So after the method has finished running, the only way to reach object B
is event in class A.
Correct.
How GC works in this case? Is it remove object B? If not than it may be a
memory leak here!!!
Technically, it's not a memory leak because B is still accessible via
A. However, that "technically" is often cold comfort to those who find
themselves in this situation. From the programmer's conceptual level,
then, it may be a "memory leak": memory that's sticking around when the
programmer intended that it be GC'd.
Remember: event delegates are just pointers. If B subscribes to an
event of A, then A contains a pointer to B, and, as such, B is not
eligible for garbage collection until A is.
However, here's an even worse example.
You have class A that exposes a _static event_ OnActionStatic. B
subscribes to OnActionStatic and then the only other reference to B
goes out of scope. Now B will never be garbage collected until the
program terminates, because the static event chain lives for the life
of the program.
There are two ways to solve this problem.
1. Before B goes out of scope, unsubscribe from the offending event so
that there are no more references to B and it is therefore eligible for
GC.
2. B subscribers to A's event via a "weak reference delegate". You can
search this group's archives for "weak reference delegate" for details.
Basically this says, "This reference (the event subscription) doesn't
count as a live reference when determining whether to garbage collect
this object."
I use number 2, myself. I have lots of static events in my system and
objects always subscribe to them via weak reference delegates.