Question

Have built a simple SerialPort client and server to test writing to and reading from COM ports. The problem is that when I attempt to read, it hangs. I know that the serial port communication itself is working fine, because I transmit from a terminal server and receive data back on a hyperterminal client app no problem. Here is the code for my server:

public partial class Form1 : Form
{
    SerialPort Port = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);

    public Form1()
    {
        InitializeComponent();
    }

    private void btnSendText_Click(object sender, EventArgs e)
    {
        Port.Open();
        Port.Write(txtSendText.Text + "!%");
        Port.Close();
    }
}

Here is the code for my client:

    private System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    public Form1()
    {
        InitializeComponent();
        this.port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.port_DataReceived);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CheckForIllegalCrossThreadCalls = false;
        if (port.IsOpen == false)
            port.Open();
    }

    private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        textBox1.Text = (port.ReadTo("!%"));
        if (port.ReadExisting().Length == 0)
        {
            listBox1.Items.Add(textBox1.Text);
            textBox1.Text = "";
        }
    }

Have been troubleshooting this over and over in a debugger with all kinds of different type of SerialPort read overloads, but it still hangs on port.ReadTo(...). Does anyone have any suggestions? TIA.

Was it helpful?

Solution

Thank you to everyone who posted. It turns out that I was using SharpDevelop_4.4.1.9729 to build and debug the application. When I read this post, I became suspicious of the open source IDE debugger,

http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed9605b6-3c97-4b53-949a-f56f9da58306/serialport-hang?forum=netfxbcl

So I tried it again instead, this time using Microsoft Visual Studio 2010 Professional, and it worked with no problem!

UPDATE:

Also, if I choose the option to "Run without debugger" in Sharp Develop, it also works without hanging, so it definitely is a problem with the Sharp Develop debugger.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top