in my app’ i’m recieving data from serial port and save them into two bool arrays.
And depends on these array i’m setting checkboxes. But checkboxes are not updating only when i change the tabs….
Here’s how i’m doin’ it(maybe there’s better way how to do it)
private void comboBoxCommunication_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (serialPort.IsOpen)
{
recieveThread.Abort();
serialPort.Close();
}
ComboBoxItem cbi = (ComboBoxItem)comboBoxCommunication.SelectedItem;
portCommunication = cbi.Content.ToString();
serialPort.PortName = portCommunication;
try
{
serialPort.Open();
recieveThread = new Thread(dataRecieving);
prijmiThread.Start();
checkBoxI1.IsChecked = vstupy[0] ? true : false;
checkBoxI2.IsChecked = inputs[1] ? true : false;
checkBoxI3.IsChecked = inputs[2] ? true : false;
checkBoxQ2.IsChecked = outputs[3] ? true : false;
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
}
}
private void dataRecieving()
{
if (serialPort.IsOpen)
{
int i = serialPort.ReadChar();
if (i == 'A')
{
inputs[0] = true;
}
else if (i == 'a')
{
inputs[0] = false;
}
if (i == 'B')
{
inputs[1] = true;
}
else if (i == 'b')
{
inputs[1] = false;
}
if (i == 'C')
{
inputs[2] = true;
}
else if (i == 'c')
{
inputs[2] = false;
}
if (i == 'D')
{
outputs[0] = true;
}
else if (i == 'd')
{
outputs[0] = false;
}
}
}
Assuming you are tying to launch a thread that checks the serial port and then have your GUI update in near-real time to changes that come across the serial thread you probably need to do several things.
I wrote up a blog entry once on an idiom for handling cross threading on Winform apps.
I’m also not sure how your inputs array is defined, but in general it’s not a good idea for two threads to be accessing shared data without some type of control mechanism. If your array is based on a data type that does atomic read/writes it might be OK but typically you want to consider what happens if one thread is in the middle of a non-atomic write when another thread either reads or writes the same data. Lots of material abounds on thread safety that you probably want to become familiar with.