串口,复选框,线程

时间:2012-02-24 16:12:47

标签: c# multithreading serial-port

嗨我只想在选择TabItem1时从串口接收6个字节。 并设置复选框状态取决于该字节... 示例:但它不起作用:/

private void receiveData()
{            
    for(int i = 0; i < 3; ++i)          
        inputs[i] = serialPort.ReadByte();
    for (int i = 0; i < 3; ++i)          
        outputs[i] = serialPort.ReadByte();

    checkBoxI1.IsChecked = inputs[0] == 32 ? true : false;
    checkBoxI2.IsChecked = inputs[1] == 32 ? true : false;
    checkBoxI3.IsChecked = inputs[2] == 32 ? true : false;
    checkBoxQ1.IsChecked = outputs[0] == 32 ? true : false;
    checkBoxQ2.IsChecked = outputs[1] == 32 ? true : false;
    checkBoxQ3.IsChecked = outputs[2] == 32 ? true : false;
}
// Tab change
private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (tabControl1.SelectedItem == tabItem1)
    {                                     
        serialPort.Close();
        try
        {
            receiveThread.Abort();
        }
        catch (NullReferenceException)
        { 
        }
    }
    else if (tabControl1.SelectedItem == tabItem2)
    {                
        serialPort.Open();                
        receiveThread = new Thread(receiveData);
        receiveThread.Start();                
    }
}

1 个答案:

答案 0 :(得分:1)

我认为receiveData函数绑定到SerialPort.DataReceived事件。事实上,这将在与你的gui不同的线程上运行。并且你喜欢在你的gui上改变一些导致所显示问题的东西。

为了让这个工作你应该打电话

checkBoxI1.Invoke(new Action(() => 
{
    checkBoxI1.IsChecked = inputs[0] == 32;
    checkBoxI2.IsChecked = inputs[1] == 32;
    checkBoxI3.IsChecked = inputs[2] == 32;
    checkBoxQ1.IsChecked = outputs[0] == 32;
    checkBoxQ2.IsChecked = outputs[1] == 32;
    checkBoxQ3.IsChecked = outputs[2] == 32;
}));

这将切换回gui线程以进行这些更改,异常应该消失。