System.IO.IOException: A device attached to the system is not functioning C# .NET 4.0

后端 未结 3 1586
北荒
北荒 2021-02-05 04:07

I\'ve built a C# application which reads and writes data from a serial port. The device connected to the serial port is a FTDI USB to serial converter which communicates to hard

3条回答
  •  长情又很酷
    2021-02-05 05:04

    In my experience 9 times out of 10 this happens when another thread (terminated or not) doesn't have exclusive access to the hardware port.

    Try writing a wrapper for the port operations, most importantly the open/closing of it, using SyncLock. https://msdn.microsoft.com/en-us/library/3a86s51t.aspx

    On a similar note, I would generally consider try/catches controlling hardware a bad practice, unless there's adequate exception handling.

    The reason (which could apply here) is that in the case where an exception is thrown the hardware will lock, and what is worse, the exception will mask the true cause of the error(s).

    In the code above I see output of messages in the style

    DebugPrint(ex.Message); 
    

    it would be quite better to do this like

    DebugPrint(ex.tostring()); 
    

    as this will also export the stack trace in the exception.

    What I would do is implement an exception logger that writes those exceptions to a (time stamped) text file somewhere in the computer this is running. Following on the exception data logged (along with all pertinent information) can lead to a better understanding why exactly this happens.

提交回复
热议问题