2

I'm using com0com to create a part of virtual ports comA/comB, typing the input to comA from hyperterminal and listening on comB in a wpf application. When I run the following code (by triggering Connect), the application successfully connects and is able to get the data from comA, but hangs when I do 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)
            {
            }
        }
    }

I tried changing the Read function to a write by using

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

instead of port.readbyte, and it starts working perfectly when disconnecting. Does anyone know if there is anything different about readbyte that could have caused the freeze? Or is it possibly related to com0com?

nemesis
  • 253
  • 1
  • 4
  • 11

1 Answers1

1

Just checking back, in case anyone runs into the same issue, I found an alternative way overriding SerialPort.DataReceived like this:

    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);
    }
nemesis
  • 253
  • 1
  • 4
  • 11
  • For posterity any chance you could include the code? – Nanhydrin Dec 18 '14 at 15:30
  • Excellent. However, it's not entirely clear to me how this relates to the previous code. Is this a new handler that you've added and attached somewhere or would this have been referenced in your original code, but not in a bit you've included in the original post? Also, you can accept your own post as the answer. – Nanhydrin Dec 18 '14 at 16:24
  • 1
    I added to the code `port.DataReceived += OnDataReceived`, instead of using `port.readbyte` – nemesis Dec 18 '14 at 16:38