【问题标题】:Serial Port, Checkboxes, Threading串口、复选框、线程
【发布时间】:2012-02-25 00:35:10
【问题描述】:

您好,我仍然希望仅在选择 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();                
    }
}

【问题讨论】:

  • 那么它是如何“不工作”的呢?你有什么行为?到目前为止你是如何调试它的?您看到了哪些错误消息?
  • WPF/WinForms/或?为什么你设置multithreading标签,异步操作什么都没有
  • 这里checkBoxI1.IsChecked = inputs[0] == 32 ? true : false;....我得到了InvalidOperationException - 调用线程无法访问这个对象,因为另一个线程拥有它。
  • 有人编辑了我的标签...我有不同的...
  • @hradecek:不。像这样:checkBoxI3.IsChecked = inputs[2] == 32;

标签: c# multithreading serial-port


【解决方案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 线程进行这些更改,并且异常应该消失。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    相关资源
    最近更新 更多