3

(apologies if this has come up before, I've searched but not found anything for my search terms)

Given the following:

void Method1 {
    Foo _foo = new Foo();
    _foo.DataReady += ProcessData();
    _foo.StartProcessingData();
}

void ProcessData() { //do something }

StartProcessingData() is a long running method which eventually (and asynchronously) raises the DataReady event. (let's say it does a service call or something)

Now, _foo used to be a class-level variable, and the event used to be wired up in the constructor.

However, memory profiling highlighted how this would keep _foo and all its dependents in memory forever, hence my change to the above.

My question is: is there ever a case when the GC will ruin things? Method1 finishes quickly (and certainly before the event fires), which means that _foo ceases to be. However, does this mean that (because _foo keeps the references for its events) ProcessData() will never fire? Or, is the presence of the event enough to keep _foo alive past the end of the method just enough to ensure that ProcessData fires? Or is it inconclusive?

[In testing, it's worked fine - ProcessData is always called. Even making StartProcessingData take a long time, and forcing a GC collection mid-way through (using RedGate's Memory Profiler) didn't remove it. But I'd like to be sure!]

For clarification: StartProcessingData() returns immediately. The Foo object would be something like:

class Foo
{
SomeSerice _service;
event EventHandler<EventArgs> DataReady;

Foo()
{
_service = new SomeService();
_service.ServiceCallCompleted += _service_ServiceCallCompleted;
}

void StartProcessingData()
{
_service.ServiceCallAsync();
}

void _service_ServiceCallCompleted
{
DataReady(null,e);
}

So, something that abstracts and emulates a long-running, asynchronous service using events to signal significant, uh, events.


Here's a complete, working example (a console app)

class Program
        {
            static void Main(string[] args)
            {
                Class1 _class1 = new Class1();
                Console.WriteLine("Disposing of Class 1");
                _class1 = null;

                GC.Collect();

                System.Threading.Thread.Sleep(15000);
                Console.Read();

            }

        }

        internal class Class1
        {
            internal Class1()
            {
                Foo _foo = new Foo();
                _foo.DataReady += new EventHandler<EventArgs>(_foo_DataReady);

                _foo.StartProcessingData();
            }

            void _foo_DataReady(object sender, EventArgs e)
            {
                Console.WriteLine("Class 1 Processing Data");
            }
        }

        class Foo
        {
            internal event EventHandler<EventArgs> DataReady = delegate { };

            internal void StartProcessingData()
            {
                System.Threading.Timer _timer = new System.Threading.Timer(OnTimer);

                Console.WriteLine("Firing event in 10 secs");
                _timer.Change(10000, System.Threading.Timeout.Infinite);
            }

            private void OnTimer(object state)
            {
                DataReady(this, null);
            }
    }

If you run it, you'll get:

Firing event in 10 secs
Disposing of Class 1
Class 1 Processing Data
Tom Morgan
  • 2,355
  • 18
  • 29

2 Answers2

2

Let's assume that StartProcessingData() is entirely synchronous (i.e. threading is not involved). It will not return until after the event fires, and ProcessData() will be called from within _foo.StartProcessingData(). If you want to verify this, put a breakpoint in ProcessData() and look at the call stack.

So, that being said, _foo won't be out of scope when the event is fired and the handler is called, because Method1() has not returned.

Now, if threading is involved, that means the code executing in the other thread must be holding a reference to _foo; otherwise, it would be impossible for the event to be fired. Therefore, _foo is still not a candidate for garbage collection. So, in either case, you shouldn't need to be concerned about _foo getting garbage collected.

(edit)

Hooking the ServiceCallCompleted event of _service now means that _service holds a reference to _foo, preventing it from being garbage collected.

FMM
  • 4,289
  • 1
  • 25
  • 44
  • What happens in the period of time once `StartProcessingData()` finishes, before the event is raised, and when `_foo` doesn't exist? I had originally assumed that the event just wouldn't be raised, as it's sort of not there any more, but that doesn't seem to be the case. – Tom Morgan Mar 02 '12 at 15:41
  • If `StartProcessingData()` is synchronous, you are misunderstanding the order of execution; `StartProcessingData()` won't return until after the event is fired. If threading is involved, the other thread is holding a reference to `_foo` and preventing it from being garbage collected. It might help to post the code to your `Foo` object. – FMM Mar 02 '12 at 15:46
  • StartProcessingData will return immediately. I will post some pseduo code for the Foo object. To take what both of you said: this is why I'm confused. _foo keeps the reference to the callback (not the other way around), so there's nothing that stops _foo being GC'd. And once the method finishes it goes out of scope. But yet, the event still fires OK. – Tom Morgan Mar 02 '12 at 16:00
  • If StartProcessingData() returns immediately, then there's threading going on, right? If so, then the other thread has a reference to _foo, which keeps _foo alive. – FMM Mar 02 '12 at 16:06
  • 1
    I always get my head turned a little when it comes to garbage collection. I had originally thought that what FMM was correct, but then found the following SO question and thought the opposite: http://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring However, I then followed the sublink: http://stackoverflow.com/questions/185931/weakreference-and-event-handling Which had a reference to http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx .... which, turned me all the way back to my original assumption that is the same as FMM – Justin Pihony Mar 02 '12 at 16:42
  • In conclusion, FMM is correct, but I highly suggest reading through the links I provided to get a stronger understanding of GC and events. As they can be quite dangerous if not understood properly – Justin Pihony Mar 02 '12 at 16:43
  • I certainly will be reading up!! I've just posted a working example in the original question to show what's happening. I'm confused because _foo keeps a reference to the method that gets called on return, not the other way around. In my example, _foo, and _timer are created by _class1. But _class1 is removed, destroyed and not there by the time the timer fires. But, the event is raised anyway. I think FMM's edit explains it in a nutshell: "Hooking the ServiceCallCompleted event of _service now means that _service holds a reference to _foo, preventing it from being garbage collected." ... – Tom Morgan Mar 02 '12 at 16:54
  • ...and in my example, hooking the DataReady event of _foo means that _foo holds a reference to _class1, preventing it from being garbage collected. In fact, preventing it from being set to null at all? Meh, need to read more! – Tom Morgan Mar 02 '12 at 16:56
  • Thanks to you both for your extensive brain-time and explanations! Justin, mind if I mark this as answer, but will +v you also? – Tom Morgan Mar 02 '12 at 16:57
  • I deleted my wrong responses to avoid future confusion. Feel free to +1 my comment if it helped at all though :) – Justin Pihony Mar 03 '12 at 14:09
  • Great discussion here, everyone! – FMM Mar 03 '12 at 15:18
0

It's possible for an object Foo to subscribe to events from object Bar and then abandon all references to Bar without, in most cases, affecting Bar's ability to fire events, since Bar would presumably have its events triggered as a result of some thread or outside object, which could only happen if that thread or outside object had a reference to it. There are two reasons it could be important Foo keeps a reference to Bar; it's possible neither applies in your case.

  1. If `Foo` does not keep any reference to `Bar`, it may be unable to let `Bar` know if it later finds itself with no need for `Bar`'s services. It could try using the `Sender` parameter of some later event callback to unsubscribe, but there are at least two problems with that: (1) Sometimes an object will raise events on behalf of another, in which case the `Sender` property might not identify the object holding the event subscription; (2) It's possible that the event might never get raised, but the reference to the subscriber could prevent the subscriber from being eligible for garbage-collection until the publisher is.
  2. It's possible (albeit unlikely) that the only other references to `Bar`, anywhere in the system, might be `WeakReference` types, and thus if `Foo` doesn't keep a strong reference to `Bar`, the system might invalidate all those weak references, effectively causing `Bar` to disappear.

Personally I believe it's a good idea for objects to cancel all subscriptions before they are abandoned. One may expect that an event publisher will go out of scope around the time a subscriber is abandoned, but if events are left connected anything which keeps a publisher alive will uselessly keep abandoned subscribers alive. If any of those abandoned subscribers are also event publishers, their abandoned subscribers in turn may be kept alive uselessly, etc.

supercat
  • 77,689
  • 9
  • 166
  • 211