我在C#中使用虚拟串口时遇到了问题:当我调用Write函数时,它会自动抛出TimeOutException,但客户端却可以接收到数据。
只有在使用虚拟端口(我使用的是来自HDDSoftware的Free Virtual Serial Ports,带有COM12<->COM13的桥接)时才会出现这种情况。我用Visual Studio打开COM12,用Hercules打开COM13。应用程序抛出超时异常,但Hercules却接收到了消息。
无论我将读/写端口超时设置为1000ms还是1000000ms都没有关系。
谢谢!
只有在使用虚拟端口(我使用的是来自HDDSoftware的Free Virtual Serial Ports,带有COM12<->COM13的桥接)时才会出现这种情况。我用Visual Studio打开COM12,用Hercules打开COM13。应用程序抛出超时异常,但Hercules却接收到了消息。
无论我将读/写端口超时设置为1000ms还是1000000ms都没有关系。
谢谢!
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中),读操作也会立即抛出TimeOutException。
这是我进行测试时得到的结果。理应是: 12:16:06 (读取超时) 12:16:16