none
Serail Port Communication - ObjectDisposed Exception RRS feed

  • Question

  •  try
                {               
                    // Check if port used is still plugged 
                    foreach (String port in System.IO.Ports.SerialPort.GetPortNames())
                    {
                        if (port.Equals(serialPort.PortName) && serialPort.IsOpen)
                            serialPort.Close();
                    }
                    
                }
                catch (Exception error)
                {
                    activeSession = false;
                }           

    I am trying to close the serial port, when my form minimizes. It works fine until the FTD cable is plugged in the USB. But once I remove the cable, I get ObjectDisposedException "Safe Handle has been closed". Tried reading other threads, but was not able to solve my problem. Any help would be appreciated.

    Thanks!

    Friday, June 22, 2012 7:30 PM

Answers

  • Seems to me that this is a sentence which is inside a program where an event is throwed which goes before this and that one releases the handles.

    (Maybe is somewhere a dispose method on the serialPort called.)


    Success
    Cor

    • Marked as answer by RoopKumar Monday, June 25, 2012 6:48 PM
    • Unmarked as answer by RoopKumar Monday, June 25, 2012 6:48 PM
    • Marked as answer by RoopKumar Monday, June 25, 2012 6:50 PM
    Monday, June 25, 2012 5:01 PM
  • Thank you for all your help! I was trying to close serial port form two different threads. So the try catch loop was not able to catch the exception. Once I removed the close serial port command from one thread, the try catch loop was able to catch the exception, when the USB Port was unplugged.

    • Marked as answer by RoopKumar Monday, June 25, 2012 6:48 PM
    Monday, June 25, 2012 6:48 PM

All replies

  • And then what?  You caught the exception.  Can you now dispose the Port?  What's an FTD cable.
    Friday, June 22, 2012 8:58 PM
  • Hello Roopkumar

    Assuming FTD cable = USB virtual serial port.

    I'm having the same problem with a project I'm working on (C++/CLI) and as yet not resolved this.

    Though I think I've tracked the issue down to the situation, that if the USB virtual serial port is removed while the application is running the GC tries at some point to dispose of a resource which no long exists. In my case this is happening after the application closes.

    I'll continue to work on this and when I find the answer I'll post it here.

    Milton


    MFN

    Saturday, June 23, 2012 2:09 AM
  • Hello Roopkumar

    Assuming FTD cable = USB virtual serial port.

    I'm having the same problem with a project I'm working on (C++/CLI) and as yet not resolved this.

    Though I think I've tracked the issue down to the situation, that if the USB virtual serial port is removed while the application is running the GC tries at some point to dispose of a resource which no long exists. In my case this is happening after the application closes.

    I'll continue to work on this and when I find the answer I'll post it here.

    Milton


    MFN

    If you're using version 4.0 of the SerialPort you should get an unhandled exception when the app closes and it's not possible to catch the exception. Seems to be different  than what the OP describes. 
    Saturday, June 23, 2012 2:17 AM
  • Sorry, I meant the FTDI cable. In my case I get the unhandled exception, in spite of the try catch loop, when my application is running. For some reason even command System.IO.Ports.SerialPort.GetPortNames(), fails to recognize that the COMPort has been unplugged. 

    I tried to add a small routine to recogonize the insertion/removal of USB devices. The routine recognizes the removal of USB devices, but not the removal of the USB FTDI cable.

    Saturday, June 23, 2012 1:09 PM
  • Sorry, I meant the FTDI cable. In my case I get the unhandled exception, in spite of the try catch loop, when my application is running. For some reason even command System.IO.Ports.SerialPort.GetPortNames(), fails to recognize that the COMPort has been unplugged. 

    I tried to add a small routine to recogonize the insertion/removal of USB devices. The routine recognizes the removal of USB devices, but not the removal of the USB FTDI cable.


    Only you know what kind of cable you have.  But if it isn't an active cable, that is, it isn't a USB device, then removing or inserting it should have no affect.  If your problem has anything to do with unplugging a SerialPort 4.0 cable, use SerialPort 2.0.
    • Edited by JohnWein Saturday, June 23, 2012 1:52 PM
    Saturday, June 23, 2012 1:50 PM
  • System.IO.Ports.SerialPort runs on its own thread when the Open() method is called. That is why you can't catch the exception on the forms's thread.

    Here is what I do to avoid errors.

    if (!serialPort.IsOpen) { serialPort.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(serialPort_OnError); serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived); //set up other properties here } ... //close connection if (serialPort.IsOpen) { try { serialPort.ErrorReceived -= serialPort_OnError; serialPort.DataReceived -= serialPort_DataReceived; if (serialPort != null) { serialPort.Close(); serialPort.Dispose(); serialPort = null; } } catch { } } ... //resume connection serialPort = new SerialPort(this.components); serialPort.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(serialPort_OnError); serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived); //set up other properties here

    serialPort.Open(); //OnError event handler static int errorCount = 0; private void serialPort_OnError(object sender, SerialErrorReceivedEventArgs e) { string message = String.Format("{0}, {1} Com Port Errors received.", e.EventType.ToString(), ++errorCount); //log message here ... } //DataReceived event handler delegate void DataReceivedHandler(); static bool sProcessing = false; /// <summary> /// this is fired when the com port receives data /// </summary> private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (sProcessing) return; //invoke method ayncronously to avoid deadlock this.BeginInvoke(new DataReceivedHandler(Process_DataReceived)); }

    I don't know for sure if this will solve your problem. It might depend on the USB to serial port driver if you are using one.


    Dan Randolph

    Sunday, June 24, 2012 12:12 AM
  • John, FYI

    http://www.ftdichip.com/Products/Cables/USBTTLSerial.htm

    Milton


    MFN

    That can't be it.

    "I am trying to close the serial port, when my form minimizes. It works fine until the FTD cable is plugged in the USB"

    His SerialPort works fine until a cable is plugged in.  It must be a cable that is plugged into the device the SerialPort is connected to.

    I don't know how the Catch block could possibly be entered.



    • Edited by JohnWein Sunday, June 24, 2012 2:37 AM
    Sunday, June 24, 2012 2:31 AM
  • But once I remove the cable, I get ObjectDisposedException "Safe Handle has been closed".

    John,

    An exception is being thrown on the SerialPort thread because RoopKumar removed the usb cable. I suspect this was while the thread was blocked with an Invoke call from the DataReceived event handler. This will cause problems almost every time in my experience. You have to call BeginInvoke to leave the SerialPort thread free to handle cases like removing the cable or even calling serialPort.Close().


    Dan Randolph

    Sunday, June 24, 2012 2:52 AM
  • But once I remove the cable, I get ObjectDisposedException "Safe Handle has been closed".

    John,

    An exception is being thrown on the SerialPort thread because RoopKumar removed the usb cable. I suspect this was while the thread was blocked with an Invoke call from the DataReceived event handler. This will cause problems almost every time in my experience. You have to call BeginInvoke to leave the SerialPort thread free to handle cases like removing the cable or even calling serialPort.Close().


    Dan Randolph

    I don't believe it. 

    try
               
    {              
                   
    // Check if port used is still plugged
                   
    foreach (String port in System.IO.Ports.SerialPort.GetPortNames())
                   
    {
                       
    if (port.Equals(serialPort.PortName) && serialPort.IsOpen)
                            serialPort
    .Close();
                   
    }
                   
               
    }
               
    catch (Exception error)
               
    {
                    MessageBox.Show(error.ToString())
    ;
               
    } 

    Under the circumstances you describe your MessageBox Shows "Safe Handle has been closed"

    It really doesn't matter.  Until the OP clarifies what version of the SerialPort he is using and how many cables he has, these WAGs are simply that.

             

    Sunday, June 24, 2012 3:18 AM
  • Is it something we can fix? I have tried most of the suggestions in many threads, nothing seems to be working.
    Monday, June 25, 2012 1:55 PM
  • Is it something we can fix? I have tried most of the suggestions in many threads, nothing seems to be working.

    Only you know what you are trying to fix.

    All known problems with the 2.0 SerialPort have been addressed and workarounds published.

    • Edited by JohnWein Monday, June 25, 2012 3:15 PM
    Monday, June 25, 2012 3:12 PM
  • Is it something we can fix? I have tried most of the suggestions in many threads, nothing seems to be working.
    Are you using the serialPort_DataReceived event handler?

    Dan Randolph

    Monday, June 25, 2012 4:14 PM
  • Seems to me that this is a sentence which is inside a program where an event is throwed which goes before this and that one releases the handles.

    (Maybe is somewhere a dispose method on the serialPort called.)


    Success
    Cor

    • Marked as answer by RoopKumar Monday, June 25, 2012 6:48 PM
    • Unmarked as answer by RoopKumar Monday, June 25, 2012 6:48 PM
    • Marked as answer by RoopKumar Monday, June 25, 2012 6:50 PM
    Monday, June 25, 2012 5:01 PM
  • Thank you for all your help! I was trying to close serial port form two different threads. So the try catch loop was not able to catch the exception. Once I removed the close serial port command from one thread, the try catch loop was able to catch the exception, when the USB Port was unplugged.

    • Marked as answer by RoopKumar Monday, June 25, 2012 6:48 PM
    Monday, June 25, 2012 6:48 PM