Can you maybe provide me in the right direction with understanding how to get one thread communicate with another?
Starting the serial port is done using a method like this:
private void connect_Click(object sender, EventArgs e)
{
System.ComponentModel.IContainer components =
new System.ComponentModel.Container();
port = new System.IO.Ports.SerialPort(components);
port.PortName = comPort.SelectedItem.ToString();
port.BaudRate = Int32.Parse(baudRate.SelectedItem.ToString());
port.DtrEnable = true;
port.ReadTimeout = 5000;
port.WriteTimeout = 500;
port.Open();
readThread = new Thread(new ThreadStart(this.Read));
readThread.Start();
this.hardWorker.RunWorkerAsync();
connect.Text = "<Connected>";
connect.Enabled = false;
comPort.Enabled = false;
}
Where hardWorker and readThread are declared as:
private BackgroundWorker hardWorker;
private Thread readThread = null;
and hardworker is initialized as:
hardWorker = new BackgroundWorker();
(in the form's constructor).
The Read() method that the serial thread uses looks like:
public void Read()
{
while (port.IsOpen)
{
try
{
if (port.BytesToRead > 0)
{
string message = port.ReadLine();
Console.WriteLine("Read from serial port [{0}]", message);
this.SetText(message);
}
}
catch (TimeoutException) { }
}
}
where the SetText() method is declared as a delegate:
delegate void SetTextCallback(string text);
and is implemented as:
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.receiveText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.receiveText.Text += "Text: ";
this.receiveText.Text += text;
this.receiveText.Text += Environment.NewLine;
}
}
Basically, this allows the UI thread and the serial thread to call the same function. If the caller is the UI thread, the text is handled directly. If it is the serial thread, a delegate is created, and Invoke used to pass the data to the UI thread.