Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Using Using object disposal...

Using Using object disposal...

Scheduled Pinned Locked Moved C#
sharepointquestion
21 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T TheTinSoldier

    Thanks for your reply. I was pretty sure that was right. :-D Hey, but if an object doesn't implement IDisposable is there any point in using Using?

    S Offline
    S Offline
    Scott Dorman
    wrote on last edited by
    #9

    TheTinSoldier wrote:

    if an object doesn't implement IDisposable is there any point in using Using?

    If it doesn't implement IDisposable, you will get a compiler error if you try to use it in a using block.

    ----------------------------- In just two days, tomorrow will be yesterday. http://geekswithblogs.net/sdorman

    T 1 Reply Last reply
    0
    • T TheTinSoldier

      Check this code. Two questions: 1. After opening the serial port do I need to worry about closing the port as when I return (leave the using scope) the object will automatically be disposed? 2. If the code enters the catch block will the serial port object automatically be disposed after leaving the using scope? Thanks!

              public static bool IsPortInUse(string portName)
              {
                  try
                  {
                      using(SerialPort sp = new SerialPort(portName))
                      {
                          sp.Open();
                          return false;
                      }
                  }
                  catch (UnauthorizedAccessException e)
                  {
                      return true;
                  }
              }
      
      B Offline
      B Offline
      BoneSoft
      wrote on last edited by
      #10

      It actually compiles to something like this:

      public static bool IsPortInUse(string portName) {
      try {
      SerialPort sp = null;
      try {
      sp = new SerialPort(portName);
      sp.Open();
      return false;
      } catch (Exception ex) {
      throw ex;
      } finally {
      if (sp != null) {
      sp.Dispose();
      }
      }
      } catch (UnauthorizedAccessException e) {
      return true;
      }
      }

      Which will automatically dispose, even if an exception occurs.


      Try code model generation tools at BoneSoft.com.

      T 1 Reply Last reply
      0
      • T TheTinSoldier

        Check this code. Two questions: 1. After opening the serial port do I need to worry about closing the port as when I return (leave the using scope) the object will automatically be disposed? 2. If the code enters the catch block will the serial port object automatically be disposed after leaving the using scope? Thanks!

                public static bool IsPortInUse(string portName)
                {
                    try
                    {
                        using(SerialPort sp = new SerialPort(portName))
                        {
                            sp.Open();
                            return false;
                        }
                    }
                    catch (UnauthorizedAccessException e)
                    {
                        return true;
                    }
                }
        
        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #11

        Some comments: 1. you dont need to open a port to know whether it is already open; use the IsOpen property. 2. I would have nested the try and using blocks the other way around, but I dont think it matters much. 3. I did not find in MSDN doc a statement indicating that Dispose() also calls Close(); lets hope it does. Other classes have either a Dispose() or a Close() method but not both (of course you could Open() again after Close, not after Dispose). 4. SerialPort.Close (or Dispose?) does not immediately close the port, so when soon followed by a SerialPort.Open that open may fail (see second remark in MSDN doc on Close). As a result, while your method name sounds like it is only providing information, you are actually changing its state (albeit temporarily). :)

        Luc Pattyn


        try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


        B T 2 Replies Last reply
        0
        • L Luc Pattyn

          Some comments: 1. you dont need to open a port to know whether it is already open; use the IsOpen property. 2. I would have nested the try and using blocks the other way around, but I dont think it matters much. 3. I did not find in MSDN doc a statement indicating that Dispose() also calls Close(); lets hope it does. Other classes have either a Dispose() or a Close() method but not both (of course you could Open() again after Close, not after Dispose). 4. SerialPort.Close (or Dispose?) does not immediately close the port, so when soon followed by a SerialPort.Open that open may fail (see second remark in MSDN doc on Close). As a result, while your method name sounds like it is only providing information, you are actually changing its state (albeit temporarily). :)

          Luc Pattyn


          try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


          B Offline
          B Offline
          BoneSoft
          wrote on last edited by
          #12

          It does not also call Close(), only Dispose(). But most things do call Close() in their implementation of Dispose().


          Try code model generation tools at BoneSoft.com.

          L E 2 Replies Last reply
          0
          • L Luc Pattyn

            Some comments: 1. you dont need to open a port to know whether it is already open; use the IsOpen property. 2. I would have nested the try and using blocks the other way around, but I dont think it matters much. 3. I did not find in MSDN doc a statement indicating that Dispose() also calls Close(); lets hope it does. Other classes have either a Dispose() or a Close() method but not both (of course you could Open() again after Close, not after Dispose). 4. SerialPort.Close (or Dispose?) does not immediately close the port, so when soon followed by a SerialPort.Open that open may fail (see second remark in MSDN doc on Close). As a result, while your method name sounds like it is only providing information, you are actually changing its state (albeit temporarily). :)

            Luc Pattyn


            try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


            T Offline
            T Offline
            TheTinSoldier
            wrote on last edited by
            #13

            Hi Luc. In regards to your points: 1. I need to first open the port to call the IsOpen property. I am checking if the port is in use. (not by my application). 2. It would be nice to know if it does matter, as I'll do it your way if it's the right way 3. I get the feeling (from you and others) that even though the object will be disposed it wouldn't hurt to close it first. 4. This is interesting, I'd better check that out. I think for what I'm doing it should be ok. Thanks to you and everyone for their help!

            L 1 Reply Last reply
            0
            • B BoneSoft

              It does not also call Close(), only Dispose(). But most things do call Close() in their implementation of Dispose().


              Try code model generation tools at BoneSoft.com.

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #14

              Hi,

              BoneSoft wrote:

              It does not also call Close(), only Dispose().

              I am afraid you misunderstood me; you seem to think I expected the using statement to call both Close() and Dispose(). I know that is not the case. What I said was: "I did not find in MSDN doc a statement indicating that Dispose() also calls Close()". I am using the using statement quite a lot, and propagating it where ever I can. Regards

              Luc Pattyn


              try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


              1 Reply Last reply
              0
              • S Scott Dorman

                TheTinSoldier wrote:

                if an object doesn't implement IDisposable is there any point in using Using?

                If it doesn't implement IDisposable, you will get a compiler error if you try to use it in a using block.

                ----------------------------- In just two days, tomorrow will be yesterday. http://geekswithblogs.net/sdorman

                T Offline
                T Offline
                TheTinSoldier
                wrote on last edited by
                #15

                Good to know! Thanks!

                1 Reply Last reply
                0
                • B BoneSoft

                  It actually compiles to something like this:

                  public static bool IsPortInUse(string portName) {
                  try {
                  SerialPort sp = null;
                  try {
                  sp = new SerialPort(portName);
                  sp.Open();
                  return false;
                  } catch (Exception ex) {
                  throw ex;
                  } finally {
                  if (sp != null) {
                  sp.Dispose();
                  }
                  }
                  } catch (UnauthorizedAccessException e) {
                  return true;
                  }
                  }

                  Which will automatically dispose, even if an exception occurs.


                  Try code model generation tools at BoneSoft.com.

                  T Offline
                  T Offline
                  TheTinSoldier
                  wrote on last edited by
                  #16

                  That makes it clear! Thanks! :cool:

                  1 Reply Last reply
                  0
                  • T TheTinSoldier

                    Hi Luc. In regards to your points: 1. I need to first open the port to call the IsOpen property. I am checking if the port is in use. (not by my application). 2. It would be nice to know if it does matter, as I'll do it your way if it's the right way 3. I get the feeling (from you and others) that even though the object will be disposed it wouldn't hurt to close it first. 4. This is interesting, I'd better check that out. I think for what I'm doing it should be ok. Thanks to you and everyone for their help!

                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #17

                    Hi, 1. You need a SerialPort instance in order to get its IsOpen property; if you manage to open the port, you dont want IsOpen anymore since that now will always be true. 2. the one difference is whether the SerialPort constructor is in or outside the try; I would put it outside, since your method cannot cope with a failing constructor, if and when that happens, that exception really should go upstairs. But once you got the port, whatever you do to it is "internal affairs", and should be masked from the caller, hence we want that to be inside the try. 3. Assuming Dispose() calls Close() there is no need and no use in calling Close() explicitly. The Dispose() is immediate, the using statement is just a shorthand for a finally {port.Dispose()} as another poster already pointed out. :)

                    Luc Pattyn


                    try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


                    T 1 Reply Last reply
                    0
                    • L Luc Pattyn

                      Hi, 1. You need a SerialPort instance in order to get its IsOpen property; if you manage to open the port, you dont want IsOpen anymore since that now will always be true. 2. the one difference is whether the SerialPort constructor is in or outside the try; I would put it outside, since your method cannot cope with a failing constructor, if and when that happens, that exception really should go upstairs. But once you got the port, whatever you do to it is "internal affairs", and should be masked from the caller, hence we want that to be inside the try. 3. Assuming Dispose() calls Close() there is no need and no use in calling Close() explicitly. The Dispose() is immediate, the using statement is just a shorthand for a finally {port.Dispose()} as another poster already pointed out. :)

                      Luc Pattyn


                      try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


                      T Offline
                      T Offline
                      TheTinSoldier
                      wrote on last edited by
                      #18

                      All good advice. Thanks for your time luc! :-D

                      1 Reply Last reply
                      0
                      • B BoneSoft

                        It does not also call Close(), only Dispose(). But most things do call Close() in their implementation of Dispose().


                        Try code model generation tools at BoneSoft.com.

                        E Offline
                        E Offline
                        Ed Poore
                        wrote on last edited by
                        #19

                        Actually Close calls Dispose.  Take a look in reflector:

                        public class SerialPort : Component
                        {
                            public void Close()
                            {
                               this.Dispose(true);
                            }
                            protected override void Dispose(bool disposing)
                            {
                               if (disposing && this.IsOpen)
                               {
                                  this.internalSerialStream.Flush();
                                  this.internalSerialStream.Close();
                                  this.internalSerialStream = null;
                               }
                               base.Dispose(disposing);
                            }
                        }


                        My Blog[^]

                        L 1 Reply Last reply
                        0
                        • E Ed Poore

                          Actually Close calls Dispose.  Take a look in reflector:

                          public class SerialPort : Component
                          {
                              public void Close()
                              {
                                 this.Dispose(true);
                              }
                              protected override void Dispose(bool disposing)
                              {
                                 if (disposing && this.IsOpen)
                                 {
                                    this.internalSerialStream.Flush();
                                    this.internalSerialStream.Close();
                                    this.internalSerialStream = null;
                                 }
                                 base.Dispose(disposing);
                              }
                          }


                          My Blog[^]

                          L Offline
                          L Offline
                          Luc Pattyn
                          wrote on last edited by
                          #20

                          Hi Ed, there must be a mistake somewhere; MSDN on SerialPort.Close explains: 1. Close() disposes of the internal streams (sounds OK) 2. you can Open() a port after it has been closed (cant be true if Close disposes of port) :confused:

                          Luc Pattyn


                          try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


                          E 1 Reply Last reply
                          0
                          • L Luc Pattyn

                            Hi Ed, there must be a mistake somewhere; MSDN on SerialPort.Close explains: 1. Close() disposes of the internal streams (sounds OK) 2. you can Open() a port after it has been closed (cant be true if Close disposes of port) :confused:

                            Luc Pattyn


                            try { [Search CP Articles] [Search CP Forums] [Forum Guidelines] [My Articles] } catch { [Google] }


                            E Offline
                            E Offline
                            Ed Poore
                            wrote on last edited by
                            #21

                            Luc Pattyn wrote:

                            you can Open() a port after it has been closed (cant be true if Close disposes of port)

                            Looking at the code more deeply all that the base.Dispose(true) does is remove the component from the container and fires the Disposed event.  So looks like it may remain usable.


                            My Blog[^]

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups