我有一个虚拟COM设备(从USB到UART),正在尝试使用C#SerialPort命令。当我调用Write或WriteLine方法时,得到以下堆栈跟踪:
Exception (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.EndWrite(IAsyncResult asyncResult)
at System.IO.Ports.SerialStream.Write(Byte[] array, Int32 offset, Int32 count, Int32 timeout)
at System.IO.Ports.SerialPort.Write(String text)
我已经通过设备文档以及通过PuTTY的成功通信确认了端口,波特率,奇偶校验和握手,所以问题肯定出在我的C#代码上。
_serialPort = new SerialPort(commId, 9600, Parity.None, 8, StopBits.One)
{
Handshake = Handshake.XOnXOff,
ReadTimeout = 5000,
WriteTimeout = 5000,
NewLine = "\r", //added during debug
DtrEnable = true, //added during debug
RtsEnable = true //added during debug
};
_serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
_serialPort.Open();
_serialPort.DiscardInBuffer(); //added during debug
_serialPort.DiscardOutBuffer(); //added during debug
_serialPort.Write("echo");
_serialPort.WriteLine("echo");