串行端口中的ReadExisting()会引发I / O异常

时间:2011-11-08 03:35:47

标签: c# .net serial-port

我们正在从.Net 2.0中的SerialPort读取数据。但在阅读之前,我们确保串口中没有任何内容。所以我们要等到串行端口缓冲区为空。

以下是代码:

SerialCommunicationPort.SerialPort.BaudRate = 300;
SerialCommunicationPort.SerialPort.Parity = Parity.None;
SerialCommunicationPort.SerialPort.StopBits = 1;
SerialCommunicationPort.SerialPort.DataBits = 7;
SerialCommunicationPort.SerialPort.ReadTimeout = 1;
SerialCommunicationPort.SerialPort.RtsEnable = true;
SerialCommunicationPort.SerialPort.DtrEnable = true;
SerialCommunicationPort.SerialPort.WriteTimeout = 1500; 

do
{
    strTempRecv = SerialCommunicationPort.SerialPort.ReadExisting();
    if (string.IsNullOrEmpty(strTempRecv))
    {
        Thread.Sleep(100);
        intTimeOut++;
    }
    else
    {
        intTimeOut = 0;
    }
} while (intTimeOut < 50);

如果外部设备以某种波特率(例如4800)将数据发送到串行端口,我们的应用程序将在300接收该数据。经过一段时间后,上面的Do-While循环抛出此IO异常:

System.IO.IOException: The I/O operation has been aborted because of either a thread exit or an application request.

   at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   at System.IO.Ports.SerialStream.BeginReadCore(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object stateObject)
   at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count, Int32 timeout)
   at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count)
   at System.IO.Ports.SerialPort.ReadExisting()

0 个答案:

没有答案