开发者

Getting error only first time I communicate with my SerialPort later on its working fine

  • I have a USB device (e.g. barcode scanner etc.)
  • I communicate with it using SerialPort (which is found nicely from toolbox of VS2008)

My problem is:

After starting my PC when starting my application for the first time it is hanging up or stuck up or going into not responding mode when it tries to sending a string to the serial port.

To come out of it I just remove the USB cable from the USB port of my PC.

As soon as I remove the cable I getting below error message:

Getting error only first time I communicate with my SerialPort later on its working fine

If I press the Continue button plug the removed USB cable back in my application working fine.

Note: I am getting this error only when 开发者_如何学JAVAI start my app first time after starting or restarting my PC. Afterwards it's working fine as I wanted.

Note: Another thing to consider is that if I put my code in try and catch I catch the exception only when I remove the USB cable from my PC.

Edit:

After restarting my PC, if I do

  1. plug out and then plug in the USB cable from the USB Port of the PC, and then
  2. I start my App then it's working fine

It seems to me that the control is going inside an infinite loop when i try sending a string to the serial port at the very first time after starting of the PC.

See the details of my code over here


The 90% odds here are that you are trying to work around a common deadlock scenario with SerialPort. It is common to get triggered when you use Invoke() in your DataReceived event handler. If you then use Close() in your main thread while the port is busy receiving data then a deadlock is common. Close cannot complete until the DataReceived event handler completed running, Invoke() cannot complete because the main thread is stuck in the Close call. Jerking out the connector works because the ThreadExceptionDialog pumps messages, allowing the Invoke to complete.

A simple workaround is to use BeginInvoke() instead. Just not calling Close is fine too, Windows takes care of it when your program terminates. Some sort of controlled shutdown of your app so that you don't lose anything sent by the serialport device is best.


You must close the serial port in the FormClose event. Because, port is once open your application and close the port on the application end

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜