如何使用线程自动更新标签

时间:2014-06-09 09:31:44

标签: c# multithreading winforms visual-studio-2010

我想从mod bus协议获取数据并使用标签在Windows窗体中自动显示和更新它。但是我遇到了一个问题,我必须单击按钮来显示更新的数据,而不是标签自动显示。我的代码在下面,有人可以指出我错在哪里以及如何纠正它。非常感谢:))

private void Call() {

    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];
    }
 }

1 个答案:

答案 0 :(得分:0)

用以下内容替换您的代码:

private void run(string data) {

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

    this.Invoke(new MethodInvoker(delegate {labelO2.Text = data;}));

}