Updating object value of a Form by a thread

0

I need 2 labels in my form to be updated every 1 second, so I made a thread in load of Form :

Thread threadUpdate = new Thread(new ThreadStart(UpdateState));
threadUpdate.Start();

And my UpdateState method is found as follows:

private void UpdateState()
    {
        ChangeAutoRestartValue();
        ChangeShellValue();

        Thread.Sleep(1000);
        UpdateState();
    }

Both methods within my UpdateState are to update the specific labels, but since it is not the main thread that is updating the value of these labels, it does not allow this to be done. How can I update the value of these labels using this thread to update their values?

    
asked by anonymous 15.07.2014 / 17:04

2 answers

3

In windows, who "paints" the controls on the screen is the main message loop, in response to a windows event (WM_PAINT). Therefore, you can not update values in the controls of another thread.

Only the main thread redraws the controls.

To work around this behavior, there is an "Invoke" method, in the "Control" class from which all visual controls inherit. You can use this method to update the control data.

The Invoke method asks the main thread to update the value.

The complete MSDN reference follows: link

    
15.07.2014 / 18:38
0

You should not use a normal thread to make changes to the Form. In addition, use BackgroundWorker Class . Here's an example.

    
15.07.2014 / 17:36