我在 C# 中遇到了虚拟串行端口的问题:当我调用 Write 函数时,它会自动抛出 TimeOutException,但客户端会收到数据。
它只发生在虚拟端口上(我正在使用 HDDSoftware 的免费虚拟串行端口,带有桥 COM12<->COM13)。我用 Visual Studio 打开 COM12,用 Hercules 打开 COM13。应用程序抛出超时异常,但 Hercules 收到消息。
我设置 1000 毫秒或 1000000 毫秒的读/写端口超时都没关系。
谢谢!!
using (SerialPort port = new SerialPort("COM13"))
{
// configure serial port
port.BaudRate = 9600;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.Open();
port.ReadTimeout = 10000;
byte[] buffer = Encoding.ASCII.GetBytes("HELLO WORLD");
try
{
port.Write(buffer, 0, buffer.Length);
}
catch(TimeoutException)
{
Console.WriteLine("Write timeout");
}
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
try
{
byte[] buf = new byte[100];
port.Read(buf, 0, 1);
}
catch(IOException)
{
Console.WriteLine("Read timeout");
}
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
}
经过几次测试(将 Write 放入 try-catch 中),Read 操作也会立即抛出 TimeOutException。
这是我在运行测试时得到的。它应该是:12:16:06(读取超时)12:16:16