When does the Finalize event of a class fire?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Barry Flynn

    When does the Finalize event of a class fire?

    VB 2005.

    I have the following code in a Sub.

    Dim oFred As SillyClass
    oFred = New SillyClass
    oFred.Gloop()
    oFred = Nothing

    Exit Sub

    The Finalize code in the class does not fire until the .exe is closed.
    I expected it to fire at either:-
    - the point at which oFred is set to Nothing, or
    - the point at which we exit from the Sub, and variable oFred goes out of
    scope.

    What are the rules governing when the Finalize code runs?

    Thanks

    Barry


  • Patrice

    #2
    Re: When does the Finalize event of a class fire?

    Neither, this is called by the garbage collector on which .NET memory
    management is based.

    Try :

    http://msdn.microsoft.com/en-us/library/0s71x931.aspx for finalize details
    and more generally http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx for
    the Garbage Collector itself...

    --
    Patrice


    "Barry Flynn" <Anonymousea écrit dans le message de groupe de discussion :
    uNGWR2TzIHA.392 0@TK2MSFTNGP02. phx.gbl...
    VB 2005.
    >
    I have the following code in a Sub.
    >
    Dim oFred As SillyClass
    oFred = New SillyClass
    oFred.Gloop()
    oFred = Nothing
    >
    Exit Sub
    >
    The Finalize code in the class does not fire until the .exe is closed.
    I expected it to fire at either:-
    - the point at which oFred is set to Nothing, or
    - the point at which we exit from the Sub, and variable oFred goes out of
    scope.
    >
    What are the rules governing when the Finalize code runs?
    >
    Thanks
    >
    Barry
    >
    >

    Comment

    • Phill W.

      #3
      Re: When does the Finalize event of a class fire?

      Barry Flynn wrote:
      The Finalize code in the class does not fire until the .exe is closed.
      I expected it to fire at either:-
      - the point at which oFred is set to Nothing, or
      - the point at which we exit from the Sub, and variable oFred goes out of
      scope.
      Read up on "Garbage Collection" and the "IDisposabl e" pattern (or
      Interface).

      The CLR will reclaim only Managed memory /if/ and when it needs to, i.e.
      when it needs to allocate some /more/ memory to something else. For a
      program as simple as the one you showed, it doesn't need to do so, so
      the memory doesn't get reclaimed until the program dies.

      Setting objects to Nothing in Visual Basic is [usually] a pointless
      exercise. It does /not/ get rid of the object but, instead, just makes
      it "eligible" for Garbage Collection which, as I've said, might take a
      very long time to run and get rid of the object.

      Please Note: This usually /does not/ matter.

      You only need to "worry" about it if your class uses any "unmanaged"
      resources. A simple example might be a file that you use for munging
      data around through some external tool; when your object dies, it really
      ought to "tidy up" (delete) its temporary file.

      For things like this, implement the IDisposable pattern and have your
      "client" code call the object's Dispose() method.

      Class X
      Implements IDisposable

      Sub Finalize()
      Me.Dispose( False )
      End Sub

      Public Sub Dispose()
      Implements IDisposable.Dis pose

      Me.Dispose( True )

      ' If we've cleaned up after ourselves, we can /lighten/
      ' GC's load by telling it to /ignore/ this object.
      GC.SuppressFina lize( Me )

      End Sub

      Private Sub Dispose( ByVal disposing as Boolean )
      If ( disposing ) Then
      ' Called from "our" code, we can kill off "related" objects

      If ( File.Exists( m_sTemporaryFil ePath ) ) Then
      File.Kill( m_sTemporaryFil ePath )
      End If

      End If

      ' Otherwise, we've been called from the finaliser,
      ' Other objects may or may not exist,
      ' so we only do our /own/ stuff.

      End Sub

      End Class


      Module Y
      Sub Main()
      Dim x2 as New X()

      x2.DoSomething( )
      x2.DoSomethingE lse()
      x2.DoSomethingE lseAgain()

      ' then, the important bit
      x2.Dispose()

      End Sub
      End Module

      HTH,
      Phill W.

      Comment

      • Cor Ligthert[MVP]

        #4
        Re: When does the Finalize event of a class fire?

        Barry,

        It is managed code, which means as you have to bother about finalizing, then
        start again with your design.

        The clean up is done by Net, as it is fact so difficult that you cannot do
        that anymore yourself.

        Cor

        "Barry Flynn" <Anonymouseschr eef in bericht
        news:uNGWR2TzIH A.3920@TK2MSFTN GP02.phx.gbl...
        VB 2005.
        >
        I have the following code in a Sub.
        >
        Dim oFred As SillyClass
        oFred = New SillyClass
        oFred.Gloop()
        oFred = Nothing
        >
        Exit Sub
        >
        The Finalize code in the class does not fire until the .exe is closed.
        I expected it to fire at either:-
        - the point at which oFred is set to Nothing, or
        - the point at which we exit from the Sub, and variable oFred goes out of
        scope.
        >
        What are the rules governing when the Finalize code runs?
        >
        Thanks
        >
        Barry
        >
        >

        Comment

        • rowe_newsgroups

          #5
          Re: When does the Finalize event of a class fire?

          The clean up is done by Net

          Dangerous words Cor.

          I know that this is a very sore topic between us, but in my opinion
          you can help .NET do the clean up by calling Dispose on IDisposable
          objects when you're done with them and not letting this be done by the
          GC / Finalizer.

          Thanks,

          Seth Rowe [MVP]

          Comment

          • Rory Becker

            #6
            Re: When does the Finalize event of a class fire?

            >The clean up is done by Net
            >>
            Dangerous words Cor.
            >
            I know that this is a very sore topic between us, but in my opinion
            you can help .NET do the clean up by calling Dispose on IDisposable
            objects when you're done with them and not letting this be done by the
            GC / Finalizer.

            Since Moving to VB 8 and then 9 in quick succession I have found the new
            "Using" keyword very useful here.

            --
            Rory


            Comment

            • Barry Flynn

              #7
              Re: When does the Finalize event of a class fire?

              Thanks for the various responses.

              Barry


              "Barry Flynn" <Anonymousewrot e in message
              news:uNGWR2TzIH A.3920@TK2MSFTN GP02.phx.gbl...
              VB 2005.
              >
              I have the following code in a Sub.
              >
              Dim oFred As SillyClass
              oFred = New SillyClass
              oFred.Gloop()
              oFred = Nothing
              >
              Exit Sub
              >
              The Finalize code in the class does not fire until the .exe is closed.
              I expected it to fire at either:-
              - the point at which oFred is set to Nothing, or
              - the point at which we exit from the Sub, and variable oFred goes out of
              scope.
              >
              What are the rules governing when the Finalize code runs?
              >
              Thanks
              >
              Barry
              >
              >

              Comment

              • Cor Ligthert[MVP]

                #8
                Re: When does the Finalize event of a class fire?

                Seth,

                There is a differnce what you can do and what you should do.

                What is the sense to clean up memory and resources as there is more then
                enough available, while the managed code can do that in fact better and
                cleaner.

                It sounds for me a little bit the same as that you remove every evening
                almost all the petrol out of your car to be able to go to a gas station in
                the morning and be able to get every morning the same new quantity of
                petrol.

                However, if you like to do that, feel free.

                Cor

                "rowe_newsgroup s" <rowe_email@yah oo.comschreef in bericht
                news:3390617c-f960-4f8c-afe9-012f1033aac6@x4 1g2000hsb.googl egroups.com...
                >The clean up is done by Net
                >
                Dangerous words Cor.
                >
                I know that this is a very sore topic between us, but in my opinion
                you can help .NET do the clean up by calling Dispose on IDisposable
                objects when you're done with them and not letting this be done by the
                GC / Finalizer.
                >
                Thanks,
                >
                Seth Rowe [MVP]
                >

                Comment

                • Tom Shelton

                  #9
                  Re: When does the Finalize event of a class fire?

                  On 2008-06-14, Cor Ligthert[MVP] <notmyfirstname @planet.nlwrote :
                  Seth,
                  >
                  There is a differnce what you can do and what you should do.
                  >
                  What is the sense to clean up memory and resources as there is more then
                  enough available, while the managed code can do that in fact better and
                  cleaner.
                  >
                  It sounds for me a little bit the same as that you remove every evening
                  almost all the petrol out of your car to be able to go to a gas station in
                  the morning and be able to get every morning the same new quantity of
                  petrol.
                  >
                  However, if you like to do that, feel free.
                  >
                  Cor
                  What exactly are you suggesting here, Cor? That you should not call dispose
                  on disposable objects? If so, that seems like just plain bad advice to me.
                  Not only can you tie up unmanaged resources for longer periods then are
                  necessary, you can actually affect the performance of GC itself. Considering
                  that most disposable objects also override finalize.... If you do not call
                  dispose on them, then the GC will and that means that gc will have to interact
                  with that object twice to remove it. I realize, there are some objects that
                  derive from component that it's probably safe to ignore dispose - but, I
                  certainly wouldn't suggest that as normal or best practice...

                  If I misunderstood your suggestion, then please forgive my rant :)

                  --
                  Tom Shelton

                  Comment

                  • Cor Ligthert[MVP]

                    #10
                    Re: When does the Finalize event of a class fire?

                    You mistunderstood my message however, something you added is something I
                    disagree with you.

                    In my idea you should use dispose as it is needed and were it is made for,
                    not because that is there given because it is inheritted by component.

                    I have too often read the sentence, it is a method in the class so it is
                    best practise to use it. I get the idea you write that in a way.

                    It is for me not good practise to use an method, just because that it is in
                    a class. I don't use ToString as I need to count two integers.

                    Dim a as integer = 1
                    Dim b as integer = 1
                    Dim C as integer = Cint(a.ToString ) + Cint(b.ToString )

                    In that way as is written so often wrong about dispose this above would be
                    also best practise. For me it's not.

                    There is in my idea nothing wrong with doing someting twice as that makes
                    the total proces shorter, especially as that is done at the best managed
                    moment.

                    (This including that the "using" automaticly executes dispose, what makes
                    the using at least more simple to describe)

                    Which does not mean that I don't use dispose, I always use that for drawing
                    objects, dialogforms, etc.

                    Just my idea.

                    Cor




                    "Tom Shelton" <tom_shelton@co mcastXXXXXXX.ne tschreef in bericht
                    news:wIudnaEMfN Jn8c7VnZ2dnUVZ_ oWdnZ2d@comcast .com...
                    On 2008-06-14, Cor Ligthert[MVP] <notmyfirstname @planet.nlwrote :
                    >Seth,
                    >>
                    >There is a differnce what you can do and what you should do.
                    >>
                    >What is the sense to clean up memory and resources as there is more then
                    >enough available, while the managed code can do that in fact better and
                    >cleaner.
                    >>
                    >It sounds for me a little bit the same as that you remove every evening
                    >almost all the petrol out of your car to be able to go to a gas station
                    >in
                    >the morning and be able to get every morning the same new quantity of
                    >petrol.
                    >>
                    >However, if you like to do that, feel free.
                    >>
                    >Cor
                    >
                    What exactly are you suggesting here, Cor? That you should not call
                    dispose
                    on disposable objects? If so, that seems like just plain bad advice to
                    me.
                    Not only can you tie up unmanaged resources for longer periods then are
                    necessary, you can actually affect the performance of GC itself.
                    Considering
                    that most disposable objects also override finalize.... If you do not
                    call
                    dispose on them, then the GC will and that means that gc will have to
                    interact
                    with that object twice to remove it. I realize, there are some objects
                    that
                    derive from component that it's probably safe to ignore dispose - but, I
                    certainly wouldn't suggest that as normal or best practice...
                    >
                    If I misunderstood your suggestion, then please forgive my rant :)
                    >
                    --
                    Tom Shelton

                    Comment

                    • Tom Shelton

                      #11
                      Re: When does the Finalize event of a class fire?

                      On 2008-06-14, Cor Ligthert[MVP] <notmyfirstname @planet.nlwrote :
                      You mistunderstood my message however, something you added is something I
                      disagree with you.
                      >
                      In my idea you should use dispose as it is needed and were it is made for,
                      not because that is there given because it is inheritted by component.
                      >
                      But, unless you dive in with reflector, or it is explicitly documented, how do
                      you know that it isn't necessary? It is definately necessary for many objects
                      that do inherit from component - how do you distinguish? And what if the
                      implementation of said object changes in the future?

                      Sure, I know how to find out if the call is necessary or not - but I
                      prefere these sort of things to be a black box. I don't really want to know
                      it's implementation details. And in general, a few clock cycles to make the
                      call isn't going to noticibly impact the performance.
                      I have too often read the sentence, it is a method in the class so it is
                      best practise to use it. I get the idea you write that in a way.
                      >
                      It is for me not good practise to use an method, just because that it is in
                      a class. I don't use ToString as I need to count two integers.
                      >
                      Dim a as integer = 1
                      Dim b as integer = 1
                      Dim C as integer = Cint(a.ToString ) + Cint(b.ToString )
                      >
                      That's sort of stretching the point, Cor. I am sure there aren't many people
                      who would do such a thing. But, I think the call to dispose falls in the
                      category of defensive coding and OOP's principle of information hiding...
                      In that way as is written so often wrong about dispose this above would be
                      also best practise. For me it's not.
                      >
                      Nobody is advocating calling methods just because they exist.
                      There is in my idea nothing wrong with doing someting twice as that makes
                      the total proces shorter, especially as that is done at the best managed
                      moment.
                      >
                      I'm not sure I get you here? Not calling dispose can negatively affect the
                      performance of the gc, because it normally has to make two passes to remove and
                      object that implements idispose if dispose insn't called... That has nothing
                      to do with being disposable of course - but the fact that most objects that
                      implement IDisposable also include a finalizer. How is that in anyway a good
                      thing?
                      (This including that the "using" automaticly executes dispose, what makes
                      the using at least more simple to describe)
                      >
                      Using is the same as calling dispose, yes. And I use it :)
                      Which does not mean that I don't use dispose, I always use that for drawing
                      objects, dialogforms, etc.
                      >
                      Just my idea.
                      >
                      With which, I respectfully disagree :)

                      --
                      Tom Shelton

                      Comment

                      • Cor Ligthert[MVP]

                        #12
                        Re: When does the Finalize event of a class fire?

                        Tom,
                        >
                        I'm not sure I get you here? Not calling dispose can negatively affect
                        the
                        performance of the gc, because it normally has to make two passes to
                        remove and
                        object that implements idispose if dispose insn't called... That has
                        nothing
                        to do with being disposable of course - but the fact that most objects
                        that
                        implement IDisposable also include a finalizer. How is that in anyway a
                        good
                        thing?
                        >
                        I have seen that the GC works as the video processor is doing its job, I am
                        not completely sure of that, but as it is like that, it is in fact null
                        time, while your dispose takes needed proces time.

                        I agree that this is not for non video processes. I am working at one at the
                        moment, it runs at night, nobody cares if it takes 2 or 6 hours.

                        Cor

                        Comment

                        • rowe_newsgroups

                          #13
                          Re: When does the Finalize event of a class fire?

                          On Jun 14, 2:30 pm, "Cor Ligthert[MVP]" <notmyfirstn... @planet.nl>
                          wrote:
                          Tom,
                          >
                          >
                          >
                          I'm not sure I get you here? Not calling dispose can negatively affect
                          the
                          performance of the gc, because it normally has to make two passes to
                          remove and
                          object that implements idispose if dispose insn't called... That has
                          nothing
                          to do with being disposable of course - but the fact that most objects
                          that
                          implement IDisposable also include a finalizer. How is that in anyway a
                          good
                          thing?
                          >
                          I have seen that the GC works as the video processor is doing its job, I am
                          not completely sure of that, but as it is like that, it is in fact null
                          time, while your dispose takes needed proces time.
                          >
                          I agree that this is not for non video processes. I am working at one at the
                          moment, it runs at night, nobody cares if it takes 2 or 6 hours.
                          >
                          Cor
                          I'm not sure how many times we've been through this conversation on
                          the newsgroups, but I'm sure we've covered all your arguments and
                          proved them to be rooted in misinformation or just plain wrong. I've
                          also seen this topic enough to know it doesn't really matter what
                          arguments we give, you aren't going to change your opinions. For this
                          reason I encourage readers of this thread who want the "full" debate
                          to do some searching in the archives.

                          However, just to restate my opinion, I believe you you should use
                          IDisposable every time unless you are absolutely sure that there is no
                          reason to call it (such as Cor's example of inherited Components).
                          This has nothing to do with calling the method simply because it
                          exists (such as Cor's attempt at saying this through his "ToString"
                          sample), it has to do with calling the method since the developer's
                          say it is necessary (even though sometimes it is not). Personnally, I
                          would not allow code to go to production that does not use the Dispose
                          functionality where it is needed (db transactions, streams, graphics,
                          etc). This to me is a worse "no-no" than writing code without having
                          Option Strict turned on.

                          Thanks,

                          Seth Rowe [MVP]

                          Comment

                          • Cor Ligthert[MVP]

                            #14
                            Re: When does the Finalize event of a class fire?

                            Seth,

                            What do you want to say with your complete message. You write exactly how I
                            think and always write about it.

                            Even in this thread I have explicitly given situations where it should be
                            used.

                            But that as well as you create your own classes where IDispose is not
                            implemented and unmanaged resources are used.

                            But not as you always tells to dispose things as datatables, datasets or a
                            Sqlconnection (the latter has the dispose implemented in the close).

                            So what do you mean with this cheap agusing message what tells nothing then
                            some demagogie.
                            I'm not sure how many times we've been through this conversation on
                            the newsgroups, but I'm sure we've covered all your arguments and
                            proved them to be rooted in misinformation or just plain wrong
                            Cor


                            "rowe_newsgroup s" <rowe_email@yah oo.comschreef in bericht
                            news:8f1357a7-e543-4641-8281-8e12e563fd6a@c6 5g2000hsa.googl egroups.com...
                            On Jun 14, 2:30 pm, "Cor Ligthert[MVP]" <notmyfirstn... @planet.nl>
                            wrote:
                            >Tom,
                            >>
                            >>
                            >>
                            I'm not sure I get you here? Not calling dispose can negatively affect
                            the
                            performance of the gc, because it normally has to make two passes to
                            remove and
                            object that implements idispose if dispose insn't called... That has
                            nothing
                            to do with being disposable of course - but the fact that most objects
                            that
                            implement IDisposable also include a finalizer. How is that in anyway
                            a
                            good
                            thing?
                            >>
                            >I have seen that the GC works as the video processor is doing its job, I
                            >am
                            >not completely sure of that, but as it is like that, it is in fact null
                            >time, while your dispose takes needed proces time.
                            >>
                            >I agree that this is not for non video processes. I am working at one at
                            >the
                            >moment, it runs at night, nobody cares if it takes 2 or 6 hours.
                            >>
                            >Cor
                            >
                            I'm not sure how many times we've been through this conversation on
                            the newsgroups, but I'm sure we've covered all your arguments and
                            proved them to be rooted in misinformation or just plain wrong. I've
                            also seen this topic enough to know it doesn't really matter what
                            arguments we give, you aren't going to change your opinions. For this
                            reason I encourage readers of this thread who want the "full" debate
                            to do some searching in the archives.
                            >
                            However, just to restate my opinion, I believe you you should use
                            IDisposable every time unless you are absolutely sure that there is no
                            reason to call it (such as Cor's example of inherited Components).
                            This has nothing to do with calling the method simply because it
                            exists (such as Cor's attempt at saying this through his "ToString"
                            sample), it has to do with calling the method since the developer's
                            say it is necessary (even though sometimes it is not). Personnally, I
                            would not allow code to go to production that does not use the Dispose
                            functionality where it is needed (db transactions, streams, graphics,
                            etc). This to me is a worse "no-no" than writing code without having
                            Option Strict turned on.
                            >
                            Thanks,
                            >
                            Seth Rowe [MVP]

                            Comment

                            • rowe_newsgroups

                              #15
                              Re: When does the Finalize event of a class fire?

                              I'll do my best to answer your questions Cor, though I am having a bit
                              of trouble understanding some of what you are saying here.
                              What do you want to say with your complete message. You write exactly how I
                              think and always write about it.
                              The purpose of my message was to encourage readers to find the
                              previous threads where we have been over this.
                              Even in this thread I have explicitly given situations where it should be
                              used.
                              Again, many of the areas where we differ in opinion is whether or not
                              you should call Dispose if you do not know whether it is needed. We've
                              covered this in other threads, and so as to not waste time here I will
                              not go over it again.
                              But that as well as you create your own classes where IDispose is not
                              implemented and unmanaged resources are used.
                              Are you saying that I never reference unmanaged code in my projects?
                              If so you are a fool for assuming that I don't do this. And I assure
                              you that when I reference unmanaged code I implement IDisposable for
                              cleanup.
                              But not as you always tells to dispose things as datatables, datasets or a
                              Sqlconnection (the latter has the dispose implemented in the close).
                              Close and Dispose methods do different things. Again so as to not
                              waste time please read the following thread:


                              So what do you mean with this cheap agusing message what tells nothing then
                              some demagogie.
                              I have no idea what demagogie is, but I'll attempt to answer what I
                              think you are asking.
                              I'm not sure how many times we've been through this conversation on
                              the newsgroups, but I'm sure we've covered all your arguments and
                              proved them to be rooted in misinformation or just plain wrong
                              Not sure how I could get any clearer. You have listed many arguments
                              against using the IDisposable pattern as it was intended and I and
                              many others have shown you in previous threads where you are mistaken,
                              however I don't think you have ever changed your opinion. Remember
                              though Cor, just because you don't understand why you are wrong or you
                              refuse to admit you are wrong does not mean you aren't still wrong.

                              Some of the many things you have said which I believe are blatantly
                              wrong are:

                              That calling Dispose is the same as calling ToString()
                              The Garbage Collector cleans up any resource better without any
                              interaction by the developer
                              The Garbage Collector runs during "idle" times and never affects
                              performance
                              Dispose should be avoided unless you absolutely know it must be called
                              More I'm sure I've forgotten

                              Again, I'm not going to list rebuttals here, I encourage readers to
                              use the archives and find the previous threads and form their own
                              opinions. As for me, I'm dropping this thread.

                              Thanks,

                              Seth Rowe [MVP]

                              Comment

                              Working...