我使用com0com创建虚拟端口comA / comB的一部分,在超级终端输入comA的输入并在wpf应用程序中侦听comB。当我运行以下代码时(通过触发Connect
),应用程序成功连接并能够从comA获取数据,但在Disconnect
时挂起。
public void Connect()
{
readPort = new SerialPort("COMB");
readPort.WriteTimeout = 500;
readPort.Handshake = Handshake.None;
readPort.Open();
readThread = new Thread(Read);
readRunning = true;
readThread.Start();
System.Diagnostics.Debug.Print("connected");
}
public void Disconnect()
{
if (!readRunning)
{
readPort.Close();
}
else
{
readRunning = false;
readThread.Join();
readPort.Close();
}
System.Diagnostics.Debug.Print("disconnected");
}
public void Read()
{
while (readRunning)
{
try
{
int readData = 0;
readData = readPort.ReadByte();
System.Diagnostics.Debug.Print("message: " + readData.ToString());
}
catch (TimeoutException)
{
}
}
}
我尝试使用
将Read函数更改为writebyte[] writeData = { 1, 2, 3 };
readPort.Write(writeData, 0, 3);
而不是port.readbyte
,它在断开连接时开始正常工作。有谁知道readbyte
有什么不同可能导致冻结?或者它可能与com0com有关?
答案 0 :(得分:1)
回过头来看,如果有人遇到同样的问题,我找到了另一种覆盖SerialPort.DataReceived
的方式:
public override void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
byte[] buf = new byte[sp.BytesToRead];
sp.Read(buf, 0, buf.Length);
receivedDataDel(buf);
}