Object garbage collection of events

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jay Dee

    #1

    Object garbage collection of events

    Object garbage collection of events

    I can not help wondering how the garbage collection system handles
    events.

    If I release all references to an object that has a void that an event
    somewhere is using I then have no access to the class holding the void
    so it should be garbage collected.

    But if an event holds a reference to a void of the class that I have
    no reference to douse the class stay in memory because something
    refers to it or is that reference removed from the event.

    Basically do I need to remove all event calls before releasing an
    object or are they removed automatically.

    I hope someone understands what I mean.

    This code thaw incomplete hopefully helps explain what I mean.

    Thank you all

    Jay Dee

    <code>

    static class Program
    {
    static void Main()
    {
    Form1 form = new Form1();
    form.myClass = new MyClass();
    form.MyEvent += new EventHandler(fo rm.myClass.MyEv entCall);
    form.myClass = null;
    Application.Run (form);
    }
    }

    public class Form1 : System.Windows. Forms.Form
    {
    MyClass myClass;

    public event System.EventHan dler MyEvent;

    public void OnMyEvent(Event Args e)
    {
    if (this.MyEvent != null)
    {
    this.MyEvent(th is, e);
    }
    }
    }

    public class MyClass
    {
    public void MyEventCall(obj ect sender, EventArgs e)
    {
    // do somthing.
    }
    }

    </code>
  • Scott M.

    #2
    Re: Object garbage collection of events

    Events do not hold refences to objects, nor does garbage collection relate
    to an object's events.

    An object is elligible for garbage collection when it has no "applicatti on
    roots", that is it is no longer reachable from any code paths in the
    application. Hooking an object up to an event handler (registering
    delegates to handle event notifications for the object) do not count as an
    application root. Only object variables count.

    -Scott


    "Jay Dee" <first180@gmail .comwrote in message
    news:a0ce3c52-a6f0-400c-be5a-624272314823@m4 4g2000hsc.googl egroups.com...
    Object garbage collection of events
    >
    I can not help wondering how the garbage collection system handles
    events.
    >
    If I release all references to an object that has a void that an event
    somewhere is using I then have no access to the class holding the void
    so it should be garbage collected.
    >
    But if an event holds a reference to a void of the class that I have
    no reference to douse the class stay in memory because something
    refers to it or is that reference removed from the event.
    >
    Basically do I need to remove all event calls before releasing an
    object or are they removed automatically.
    >
    I hope someone understands what I mean.
    >
    This code thaw incomplete hopefully helps explain what I mean.
    >
    Thank you all
    >
    Jay Dee
    >
    <code>
    >
    static class Program
    {
    static void Main()
    {
    Form1 form = new Form1();
    form.myClass = new MyClass();
    form.MyEvent += new EventHandler(fo rm.myClass.MyEv entCall);
    form.myClass = null;
    Application.Run (form);
    }
    }
    >
    public class Form1 : System.Windows. Forms.Form
    {
    MyClass myClass;
    >
    public event System.EventHan dler MyEvent;
    >
    public void OnMyEvent(Event Args e)
    {
    if (this.MyEvent != null)
    {
    this.MyEvent(th is, e);
    }
    }
    }
    >
    public class MyClass
    {
    public void MyEventCall(obj ect sender, EventArgs e)
    {
    // do somthing.
    }
    }
    >
    </code>

    Comment

    • Peter Duniho

      #3
      Re: Object garbage collection of events

      On Fri, 25 Jul 2008 18:50:22 -0700, Jay Dee <first180@gmail .comwrote:
      Object garbage collection of events
      >
      I can not help wondering how the garbage collection system handles
      events.
      >
      If I release all references to an object that has a void that an event
      somewhere is using I then have no access to the class holding the void
      so it should be garbage collected.
      What do you mean by "void"? If you mean a method or delegate, then you're
      severely abusing the word "void".
      But if an event holds a reference to a void of the class that I have
      no reference to douse the class stay in memory because something
      refers to it or is that reference removed from the event.
      >
      Basically do I need to remove all event calls before releasing an
      object or are they removed automatically.
      Assuming you are asking whether, in the code you posted, the instance of
      MyClass becomes eligible for garbage collection when "form.myCla ss = null"
      is executed, the answer is "no", the event handler is not removed
      automatically and so the MyClass instance remains reachable.

      Pete

      Comment

      • Peter Duniho

        #4
        Re: Object garbage collection of events

        On Fri, 25 Jul 2008 20:34:38 -0700, Scott M. <s-mar@nospam.nosp amwrote:
        Events do not hold refences to objects,
        Indirectly, they do.
        nor does garbage collection relate to an object's events.
        It does. Regardless of what the delegate references, an event retains a
        reference to any delegate subscribed to the event. If that delegate was
        constructed from an instance method, then it includes a reference to the
        class instance used, and so the event implicitly also includes that
        reference.
        An object is elligible for garbage collection when it has no
        "applicatti on
        roots", that is it is no longer reachable from any code paths in the
        application. Hooking an object up to an event handler (registering
        delegates to handle event notifications for the object) do not count as
        an
        application root. Only object variables count.
        There's no difference between an event and any other field in the object.
        None are actually "roots", as the class instance must be referenced by
        something else (for example, by a local variable on the stack, which
        _would_ be a root), but as long as the object itself is reachable, so too
        is anything referenced by its fields, including any events.

        Pete

        Comment

        • Peter Morris

          #5
          Re: Object garbage collection of events

          Do this in an MdiChild form
          MdiParent.Activ ated += SomeMethod;

          Then dispose of that MdiChild form. The form will not be collected until
          the main form closes.



          Pete

          Comment

          • raylopez99

            #6
            Re: Object garbage collection of events

            On Jul 25, 9:07 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
            wrote:

            I wonder: how do you manually collect a static object/variable?
            Specifically, a static class. In another thread I created a static
            class for a subform/child window that works fine but 'hangs around',
            and when the subform/child window is reopened, the static class is
            still there, and creates problems since it's part of an Event/Delegate
            model.

            RL

            Comment

            • =?ISO-8859-1?Q?G=F6ran_Andersson?=

              #7
              Re: Object garbage collection of events

              raylopez99 wrote:
              On Jul 25, 9:07 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
              wrote:
              >
              I wonder: how do you manually collect a static object/variable?
              Specifically, a static class. In another thread I created a static
              class for a subform/child window that works fine but 'hangs around',
              and when the subform/child window is reopened, the static class is
              still there, and creates problems since it's part of an Event/Delegate
              model.
              >
              RL
              The object isn't static, it's only the reference to the object that is
              static. The object is allocated on the heap just like any other object,
              and if you remove the reference from the static variable (e.g. setting
              it to null), the object can be garbage collected.

              --
              Göran Andersson
              _____
              Göran Anderssons privata hemsida.

              Comment

              • olduncleamos

                #8
                Re: Object garbage collection of events

                On Jul 25, 11:34 pm, "Scott M." <s-...@nospam.nosp amwrote:
                Events do not hold refences to objects, nor does garbage collection relate
                to an object's events.
                >
                An object is elligible for garbage collection when it has no "applicatti on
                roots", that is it is no longer reachable from any code paths in the
                application.  Hooking an object up to an event handler (registering
                delegates to handle event notifications for the object) do not count as an
                application root.  Only object variables count.
                >
                -Scott
                >
                This misunderstandin g could be costly...


                Comment

                • Jay Dee

                  #9
                  Re: Object garbage collection of events

                  I thank you all for your valuable responses.

                  Sorry for miss using the word “void” I think that I mean “method”.

                  I am still slightly confused as there seems to be two different views
                  here and I don’t know witch is correct.

                  Would I be correct in saying that in my example above a call to
                  “form.MyEvent” will not call the method “MyEventCall” as I no longer
                  have a valid reference to that method.

                  Or is that method still valid because the event its self still refers
                  to it.

                  Thank you all.

                  Jay Dee

                  Comment

                  • Peter Duniho

                    #10
                    Re: Object garbage collection of events

                    On Sat, 26 Jul 2008 10:05:11 -0700, Jay Dee <first180@gmail .comwrote:
                    [...]
                    Would I be correct in saying that in my example above a call to
                    “form.MyEvent ” will not call the method “MyEventCallâ € as I no longer
                    have a valid reference to that method.
                    No, that would be incorrect.
                    Or is that method still valid because the event its self still refers
                    to it.
                    Yes. When you subscribe to the event, a delegate is created ("new
                    EventHandler(.. .)"), and that delegate references the instance of MyClass
                    used to create the delegate. As long as the event itself is reachable, so
                    too will be anything it references, and anything that it references
                    references, and so on.

                    Just because _some_ reference to that instance of MyClass no longer
                    exists, that doesn't make the instance go away. It's only when that
                    instance of MyClass becomes "unreachabl e" that the instance may be garbage
                    collected. An instance is "reachable" if a reference to it is stored in a
                    root (such as a static field or local variable), or a reference to it is
                    stored in a data structure that is itself "reachable" (so there's a
                    recursive aspect to the definition of "reachable" , as noted above).

                    So in your example, as long as the Form1 instance is reachable, so too is
                    any class instance referenced in a delegate subscribed to an even in the
                    Form1 instance.

                    Basically: the garbage collector doesn't go around invalidating
                    references. Instead, it collects objects only when you can no longer get
                    at them.

                    Pete

                    Comment

                    • Jay Dee

                      #11
                      Re: Object garbage collection of events

                      Would I be correct in saying that in my example above a call to
                      “form.MyEvent” will not call the method “MyEventCall” as I no longer
                      have a valid reference to that method.
                      >
                      No, that would be incorrect.
                      >
                      Or is that method still valid because the event its self still refers
                      to it.
                      >
                      Yes.  When you subscribe to the event, a delegate is created ("new  
                      EventHandler(.. .)"), and that delegate references the instance of MyClass 
                      used to create the delegate.  As long as the event itself is reachable,so  
                      too will be anything it references, and anything that it references  
                      references, and so on.
                      >
                         Just because _some_ reference to that instance of MyClass no longer  
                      exists, that doesn't make the instance go away.  It's only when that  
                      instance of MyClass becomes "unreachabl e" that the instance may be garbage  
                      collected.  An instance is "reachable" if a reference to it is stored in a  
                      root (such as a static field or local variable), or a reference to it is  
                      stored in a data structure that is itself "reachable" (so there's a  
                      recursive aspect to the definition of "reachable" , as noted above).
                      >
                      So in your example, as long as the Form1 instance is reachable, so too is 
                      any class instance referenced in a delegate subscribed to an even in the  
                      Form1 instance.
                      >
                      Basically: the garbage collector doesn't go around invalidating  
                      references.  Instead, it collects objects only when you can no longer get  
                      at them.
                      >
                      Pete
                      Thank you. That was a well written response.

                      Comment

                      • Jeff Louie

                        #12
                        Re: Object garbage collection of events

                        >>Basically do I need to remove all event calls before releasing an
                        object or are they removed automatically.< <

                        Jay... As Peter suggest, using events can lead to the "lapsed listener"
                        conumdrum:



                        One solution is the weak event manager:

                        http://msdn.microsoft.com/en-us/libr...akeventmanager.
                        aspx

                        Another alternative would be supplier driven registration of listeners.

                        Regards,
                        Jeff

                        *** Sent via Developersdex http://www.developersdex.com ***

                        Comment

                        Working...