2

我正在使用 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)
            {
            }
        }
    }

我尝试通过使用将读取功能更改为写入

byte[] writeData = { 1, 2, 3 };
readPort.Write(writeData, 0, 3);

而不是port.readbyte, 断开连接时它开始正常工作。有谁知道是否有任何不同readbyte可能导致冻结?或者它可能与com0com有关?

4

1 回答 1

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);
    }
于 2014-12-18T15:18:11.237 回答