C# update GUI continuously from backgroundworker.

Posted by Qrew on Stack Overflow See other posts from Stack Overflow or by Qrew
Published on 2010-03-31T09:05:12Z Indexed on 2010/03/31 9:13 UTC
Read the original article Hit count: 890

I have created a GUI (winforms) and added a backgroundworker to run in a separate thread. The backgroundworker needs to update 2 labels continuously. The backgroundworker thread should start with button1 click and run forever.

    class EcuData 
    {
        public int RPM { get; set; }
        public int MAP { get; set; }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        EcuData data = new EcuData
        {
            RPM = 0,
            MAP = 0
        };
        BackWorker1.RunWorkerAsync(data);
    }

    private void BackWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        EcuData argumentData = e.Argument as EcuData;
        int x = 0;
        while (x<=10)
        {
            //
            // Code for reading in data from hardware.
            //
            argumentData.RPM = x;           //x is for testing only!
            argumentData.MAP = x * 2;       //x is for testing only!
            e.Result = argumentData;
            Thread.Sleep(100);
            x++;
       }
    private void BackWorker1_RunWorkerCompleted_1(object sender,  RunWorkerCompletedEventArgs e)
    {
        EcuData data = e.Result as EcuData;
        label1.Text = data.RPM.ToString();
        label2.Text = data.MAP.ToString();
    }
}

The above code just updated the GUI when backgroundworker is done with his job, and that's not what I'm looking for.

© Stack Overflow or respective owner

Related posts about c#

Related posts about backgroundworker