object.close() or object = null?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Justin Rich

    object.close() or object = null?

    so im trying to be good and not leave anything hanging open but i guess ive
    seen a variety of ways to kill objects.. is there like a recommended way?

    basically im looking for best practices for handling object destruction.

    Thanks
    Justin


  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: object.close() or object = null?

    Justin,

    If the type of the object instance implements IDisposable, then you
    should call the Dispose method on that interface implementation. The
    "using" construct is handy for that:

    using (MyObject myObject = new MyObject())
    {
    // Use myObject here.
    }

    When the scope is exited (because of return value, exception, or the
    code just exits the scope) the Dispose method is going to be called on
    MyObject's implementation of IDisposable.

    If a type doesn't implement IDisposable, then you don't have to do
    anything with the object, the CLR will take care of it eventually through
    GC.

    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m

    "Justin Rich" <jrich523@yahoo .spam.comwrote in message
    news:u76mm988HH A.5948@TK2MSFTN GP04.phx.gbl...
    so im trying to be good and not leave anything hanging open but i guess
    ive seen a variety of ways to kill objects.. is there like a recommended
    way?
    >
    basically im looking for best practices for handling object destruction.
    >
    Thanks
    Justin
    >

    Comment

    • Tom Porterfield

      #3
      Re: object.close() or object = null?

      Justin Rich wrote:
      so im trying to be good and not leave anything hanging open but i guess ive
      seen a variety of ways to kill objects.. is there like a recommended way?
      >
      basically im looking for best practices for handling object destruction.
      Like most things, there is no one size fits all answer. If the object
      is an object that connects to a resource, such as a SQL database, then
      it likely has a close method that should be called. If the object in
      its hierarchy implements IDisposable then you want to make sure its
      Dispose method is called either explicitly or implicitly by creating the
      object with the "using" keyword. If the object is just an RTW for an
      unmanaged COM object then you'll want to properly release the underlying
      come object, possibly with a call to Marshal.Release ComObject. It is
      rare that I've seen setting the object to null to have a benefit.

      But the answer varies depending on what the object is, the scope of the
      object, the needed lifetime of the object, etc.
      --
      Tom Porterfield

      Comment

      • Ben Voigt [C++ MVP]

        #4
        Re: object.close() or object = null?


        "Tom Porterfield" <tpporter@mvps. orgwrote in message
        news:OHh%237E98 HHA.1168@TK2MSF TNGP02.phx.gbl. ..
        Justin Rich wrote:
        >so im trying to be good and not leave anything hanging open but i guess
        >ive seen a variety of ways to kill objects.. is there like a recommended
        >way?
        >>
        >basically im looking for best practices for handling object destruction.
        >
        Like most things, there is no one size fits all answer. If the object is
        an object that connects to a resource, such as a SQL database, then it
        likely has a close method that should be called. If the object in its
        hierarchy implements IDisposable then you want to make sure its Dispose
        method is called either explicitly or implicitly by creating the object
        with the "using" keyword. If the object is just an RTW for an unmanaged
        COM object then you'll want to properly release the underlying come
        object, possibly with a call to Marshal.Release ComObject. It is rare that
        I've seen setting the object to null to have a benefit.
        Whether the actual cleanup action is Close, Flush, ReleaseComObjec t, or
        whatever, nearly every object provides a Dispose method that "does the right
        thing". If it implements IDisposable, call Dispose. Any other cleanup
        requirement should be considered a bug.

        The only use of "variable = null;" is when you're in the main loop of the
        thread, where your function won't close for a very long time. Or if the
        variable is a class member. Especially static members of classes will
        always be reachable so the GC sees them as being in-use and never cleans
        them up, so in that case you should null it out.
        >
        But the answer varies depending on what the object is, the scope of the
        object, the needed lifetime of the object, etc.
        --
        Tom Porterfield

        Comment

        • Jon Skeet [C# MVP]

          #5
          Re: =?ISO-8859-1?Q?object.clos e()_or_object_= 3D_null=3F?=

          Justin Rich <jrich523@yahoo .spam.comwrote:
          so im trying to be good and not leave anything hanging open but i guess ive
          seen a variety of ways to kill objects.. is there like a recommended way?
          >
          basically im looking for best practices for handling object destruction.
          You can't "kill" an object at all.

          You can ask it to release any non-memory resource it has, usually by
          calling Dispose() which can be performed automatically with a "using"
          statement.

          You can't force an object to be destroyed, however. Setting a variable
          to null doesn't force this, for three reasons:

          1) There might be other references to the object
          2) The object will only be destroyed when the garbage collector kicks
          in (and only then if it's collecting that generation)
          3) If the object has a finalizer, it will last until the subsequent
          collection

          --
          Jon Skeet - <skeet@pobox.co m>
          http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
          If replying to the group, please do not mail me too

          Comment

          • Peter Duniho

            #6
            Re: object.close() or object = null?

            Ben Voigt [C++ MVP] wrote:
            Whether the actual cleanup action is Close, Flush, ReleaseComObjec t, or
            whatever, nearly every object provides a Dispose method that "does the right
            thing". If it implements IDisposable, call Dispose. Any other cleanup
            requirement should be considered a bug.
            And IMHO the point here is that Close, etc. is not a replacement for
            Dispose. It's usually there to allow a specific kind of behavior that
            is not necessarily equivalent to calling Dispose.

            It's not an either/or thing. If a class implements IDisposeable, you
            need to call Dispose when you're done with the object. You may also
            want to use a similar (but not identical) method also implemented by the
            class.

            Pete

            Comment

            • Tom Porterfield

              #7
              Re: object.close() or object = null?

              Ben Voigt [C++ MVP] wrote:
              "Tom Porterfield" <tpporter@mvps. orgwrote in message
              >Like most things, there is no one size fits all answer. If the object is
              >an object that connects to a resource, such as a SQL database, then it
              >likely has a close method that should be called. If the object in its
              >hierarchy implements IDisposable then you want to make sure its Dispose
              >method is called either explicitly or implicitly by creating the object
              >with the "using" keyword. If the object is just an RTW for an unmanaged
              >COM object then you'll want to properly release the underlying come
              >object, possibly with a call to Marshal.Release ComObject. It is rare that
              >I've seen setting the object to null to have a benefit.
              >
              Whether the actual cleanup action is Close, Flush, ReleaseComObjec t, or
              whatever, nearly every object provides a Dispose method that "does the right
              thing". If it implements IDisposable, call Dispose. Any other cleanup
              requirement should be considered a bug.
              A runtime callable wrapper is created whenever you interop to a COM
              interface pointer from managed code. You should use
              Marshal.Release ComObject to free the underlying COM object. Yes, you
              can wait for the runtime to do this for you, just as you can wait for it
              to dispose of an object that implements IDisposable, but that can lead
              to memory issues. Having to call ReleaseComObjec t on a RCW is no more a
              bug than needing to call Dispose on an IDisposable object.
              --
              Tom Porterfield

              Comment

              • Justin Rich

                #8
                Re: object.close() or object = null?

                Thanks for the responses everyone. That helps out a lot.

                Justin

                "Justin Rich" <jrich523@yahoo .spam.comwrote in message
                news:u76mm988HH A.5948@TK2MSFTN GP04.phx.gbl...
                so im trying to be good and not leave anything hanging open but i guess
                ive seen a variety of ways to kill objects.. is there like a recommended
                way?
                >
                basically im looking for best practices for handling object destruction.
                >
                Thanks
                Justin
                >

                Comment

                • Justin Rich

                  #9
                  Re: object.close() or object = null?

                  Is that to say that if the object implements IDisposable AND has its own
                  close method that i should, to be safe, call both of them?

                  object.close();
                  object.dispose( );

                  i doubt doing this would hurt anything and for the most part should be more
                  helpful than wasteful?

                  thanks
                  Justin


                  "Peter Duniho" <NpOeStPeAdM@Nn OwSlPiAnMk.comw rote in message
                  news:13eb479jn3 cqkde@corp.supe rnews.com...
                  Ben Voigt [C++ MVP] wrote:
                  >Whether the actual cleanup action is Close, Flush, ReleaseComObjec t, or
                  >whatever, nearly every object provides a Dispose method that "does the
                  >right thing". If it implements IDisposable, call Dispose. Any other
                  >cleanup requirement should be considered a bug.
                  >
                  And IMHO the point here is that Close, etc. is not a replacement for
                  Dispose. It's usually there to allow a specific kind of behavior that is
                  not necessarily equivalent to calling Dispose.
                  >
                  It's not an either/or thing. If a class implements IDisposeable, you need
                  to call Dispose when you're done with the object. You may also want to
                  use a similar (but not identical) method also implemented by the class.
                  >
                  Pete

                  Comment

                  • Peter Duniho

                    #10
                    Re: object.close() or object = null?

                    Justin Rich wrote:
                    Is that to say that if the object implements IDisposable AND has its own
                    close method that i should, to be safe, call both of them?
                    What Nicholas said. :)

                    Comment

                    • Bob Powell [MVP]

                      #11
                      Re: object.close() or object = null?

                      If an object implements IDispose then call the Dispose method. If not then
                      set it's reference to null.

                      --
                      --
                      Bob Powell [MVP]
                      Visual C#, System.Drawing

                      Ramuseco Limited .NET consulting


                      Find great Windows Forms articles in Windows Forms Tips and Tricks


                      Answer those GDI+ questions with the GDI+ FAQ


                      All new articles provide code in C# and VB.NET.
                      Subscribe to the RSS feeds provided and never miss a new article.


                      "Justin Rich" <jrich523@yahoo .spam.comwrote in message
                      news:u76mm988HH A.5948@TK2MSFTN GP04.phx.gbl...
                      so im trying to be good and not leave anything hanging open but i guess
                      ive seen a variety of ways to kill objects.. is there like a recommended
                      way?
                      >
                      basically im looking for best practices for handling object destruction.
                      >
                      Thanks
                      Justin
                      >

                      Comment

                      • Bob Powell [MVP]

                        #12
                        Re: object.close() or object = null?

                        Darn. I have something wrong with my reader, I just noticed this has been
                        answered. Excuse the chaff.

                        --
                        --
                        Bob Powell [MVP]
                        Visual C#, System.Drawing

                        Ramuseco Limited .NET consulting


                        Find great Windows Forms articles in Windows Forms Tips and Tricks


                        Answer those GDI+ questions with the GDI+ FAQ


                        All new articles provide code in C# and VB.NET.
                        Subscribe to the RSS feeds provided and never miss a new article.


                        "Justin Rich" <jrich523@yahoo .spam.comwrote in message
                        news:u76mm988HH A.5948@TK2MSFTN GP04.phx.gbl...
                        so im trying to be good and not leave anything hanging open but i guess
                        ive seen a variety of ways to kill objects.. is there like a recommended
                        way?
                        >
                        basically im looking for best practices for handling object destruction.
                        >
                        Thanks
                        Justin
                        >

                        Comment

                        • Bob Powell [MVP]

                          #13
                          Re: object.close() or object = null?

                          Sorry, IDisposable.

                          --
                          --
                          Bob Powell [MVP]
                          Visual C#, System.Drawing

                          Ramuseco Limited .NET consulting


                          Find great Windows Forms articles in Windows Forms Tips and Tricks


                          Answer those GDI+ questions with the GDI+ FAQ


                          All new articles provide code in C# and VB.NET.
                          Subscribe to the RSS feeds provided and never miss a new article.


                          "Justin Rich" <jrich523@yahoo .spam.comwrote in message
                          news:u76mm988HH A.5948@TK2MSFTN GP04.phx.gbl...
                          so im trying to be good and not leave anything hanging open but i guess
                          ive seen a variety of ways to kill objects.. is there like a recommended
                          way?
                          >
                          basically im looking for best practices for handling object destruction.
                          >
                          Thanks
                          Justin
                          >

                          Comment

                          • Ben Voigt [C++ MVP]

                            #14
                            Re: object.close() or object = null?


                            "Tom Porterfield" <tpporter@mvps. orgwrote in message
                            news:OR2oGs98HH A.4476@TK2MSFTN GP06.phx.gbl...
                            Ben Voigt [C++ MVP] wrote:
                            >"Tom Porterfield" <tpporter@mvps. orgwrote in message
                            >>Like most things, there is no one size fits all answer. If the object
                            >>is an object that connects to a resource, such as a SQL database, then
                            >>it likely has a close method that should be called. If the object in
                            >>its hierarchy implements IDisposable then you want to make sure its
                            >>Dispose method is called either explicitly or implicitly by creating the
                            >>object with the "using" keyword. If the object is just an RTW for an
                            >>unmanaged COM object then you'll want to properly release the underlying
                            >>come object, possibly with a call to Marshal.Release ComObject. It is
                            >>rare that I've seen setting the object to null to have a benefit.
                            >>
                            >Whether the actual cleanup action is Close, Flush, ReleaseComObjec t, or
                            >whatever, nearly every object provides a Dispose method that "does the
                            >right thing". If it implements IDisposable, call Dispose. Any other
                            >cleanup requirement should be considered a bug.
                            >
                            A runtime callable wrapper is created whenever you interop to a COM
                            interface pointer from managed code. You should use
                            Marshal.Release ComObject to free the underlying COM object. Yes, you can
                            wait for the runtime to do this for you, just as you can wait for it to
                            dispose of an object that implements IDisposable, but that can lead to
                            memory issues. Having to call ReleaseComObjec t on a RCW is no more a bug
                            than needing to call Dispose on an IDisposable object.
                            RCW doesn't give you an interop smart pointer that implements IDisposable?
                            Yes, I would call that a bug. If you delete an ATL smart pointer the
                            IUnknown::Relea se method gets called. In .NET, things that own unmanaged
                            resources, and the reference count of a COM object is an unmanaged resource,
                            should provide a Dispose method to cleanup that native resource.

                            BTW the garbage collector won't dispose objects, it will only finalize them.
                            Failure to dispose IDisposable objects typically doesn't lead to memory
                            issues (shortage of memory just triggers a collection), it will lead to race
                            conditions on the unmanaged resource.
                            --
                            Tom Porterfield

                            Comment

                            • Peter Duniho

                              #15
                              Re: object.close() or object = null?

                              Ben Voigt [C++ MVP] wrote:
                              [...]
                              BTW the garbage collector won't dispose objects, it will only finalize them.
                              Assuming a correctly implemented finalizer, what's the difference?
                              Isn't the finalizer supposed to dispose the object (at least with
                              respect to unmanaged resources), by calling Dispose with the appropriate
                              flag?
                              Failure to dispose IDisposable objects typically doesn't lead to memory
                              issues (shortage of memory just triggers a collection), it will lead to race
                              conditions on the unmanaged resource.
                              I also don't understand that comment, for a few somewhat unrelated reasons:

                              1) I don't know what sort of race conditions you're talking about.
                              What code is using the unmanaged resource in a way that is racing
                              with other code?

                              2) If the pressure is on unmanaged resources, I would expect
                              failure to dispose objects to not create the resource pressure that
                              would trigger a collection. You might get a collection for some other
                              reason, but if what you're running low on are unmanaged resources then,
                              by definition, the GC doesn't know about them and won't collect when you
                              run low.

                              So how does failure to dispose IDisposable objects consistently not
                              lead to memory issues, and if it doesn't and you aren't writing threaded
                              code, why is it still important to call Dispose?

                              And finally,

                              3) As the comment relates to your first one...if there's a
                              difference between finalization and disposing, why does triggering a
                              collection (assuming one is triggered) address the failure to dispose an
                              object?

                              Your comment may make sense to people who already know everything there
                              is to know about .NET memory management, but for me (and possibly others
                              in a similar position), I think there's some room for elaboration. :)

                              Thanks,
                              Pete

                              Comment

                              Working...