【问题标题】:how to update a form from a thread如何从线程更新表单
【发布时间】:2014-06-09 06:51:53
【问题描述】:

我正在使用 mod 总线协议从板上检索数据。现在我想一直以窗口形式更新数据。但是标签只有在我点击按钮时才会更新,我的编码有问题吗?

私人无效调用(){

        do
        {
            RequestData(); //get data from mod bus 
            run(a.ToString());


        } while (operation);

    }

    delegate void CallMethod(string Data);

    private void run(string data) {

        if (this.labelO2.InvokeRequired)
        {
            SetRichBoxCallBack d = new SetRichBoxCallBack(run);
            this.Invoke(d, new object[] { data });
        }
        else {
            labelO2.Text = data;
        }

    }
    Thread thread;
    private void button1_Click(object sender, EventArgs e)
    {

        thread = new Thread(new ThreadStart(Call));
        thread.Start();

    }
   public void RequestData()
    {

        if (WriteSerialPort(setMessage, 0, 8))
        {
            Thread.Sleep(1000);
            for (i = 0; i < 19; i++)
            {

                MM[i] = (byte)serialPortBoard.ReadByte();


            }

            a = MM[11] << 8 | MM[12];
            b = (int)MM[13] << 8 | MM[14];


        }

    }

【问题讨论】:

  • 线程调用在button1_Click事件上?请尝试安排您的代码,它无处不在
  • 我已经编辑过了。抱歉代码乱码

标签: c# multithreading


【解决方案1】:

只是对 UI 更新的调用应该包含在 InvokeRequired ... 模式中 - 而不是从端口获取数据。 InvokeRequired... 模式也丢失了。

delegate void UIUpdate(object a, object b);

public void RequestData() {
  ...
  // set type and real value here ;)
  object a = null, b = null;
  var call = new UIUpdate((pa,pb) => {
      labelBin.Text = pa.ToString();
      labelO2.Text = pb.ToString();
  });
  if (this.InvokeRequired) {
    this.Invoke(call, a, b);
  } else {
    call.Invoke(a, b);
  }      
}

private void button1_Click(object sender, EventArgs e) {
  new Thread(() => {
    do {
      RequestData();  // get the data from mod bus protocol
    } while (operation);
  }).Start();    
}

编辑:

还应该只有一个读者线程;它将进行阅读;不要在一个线程中写入/读取。阅读器线程应在表单加载或表单构造函数中启动。

WriteSerialPort(setMessage, 0, 8)

应在单击按钮时直接调用,而读取应始终在单个(单独)线程中。

【讨论】:

  • 刚刚试了下,还是不能自动更新。我已经编辑了我的代码,你能帮我再过一遍吗?非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
相关资源
最近更新 更多