0

I want to get data from mod bus protocol and use the label to show and update it automatically in windows form. But I encounter a problem, I have to click the button to show the updated data instead of the label display it automatically. My code is below, can someone point out where I am wrong and how to correct it. Many thanks:)

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];
    }
 }
steven
  • 3
  • 5

1 Answers1

0

Replace your code with the below:

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

}
Ricky
  • 2,323
  • 6
  • 22
  • 22
  • Have you tried to debug your code? Is there any exception raising during execution? – Ricky Jun 09 '14 at 09:44
  • only click button can update the latest data. When I debug, there is no exception. – steven Jun 09 '14 at 09:46
  • nothing change, when I use timer, it works. But when I tried to use thread, I still need button to make it update – steven Jun 09 '14 at 09:51
  • Do one thing. In `public void RequestData()` function, comment all the code and update one variable. Assign this variable to label text. For example: Take one global integer variable, increment it in RequestData function and show it on the label and check whether it works or not. I tried to run your code like that and the label is updating properly. – Ricky Jun 09 '14 at 09:57
  • I tried, but it can only show the latest update. I want to show user the update process. Any way to improve it? – steven Jun 10 '14 at 01:28
  • There is one possibility that when you click a button once, a thread is created which updates the label. Now when you click that button again, one more thread will be created which will update the same label. Hence, the problem occurs. – Ricky Jun 10 '14 at 04:35