Updating object value of a Form by a thread

Asked

Viewed 1,834 times

0

I need 2 Abels of my form to be updated every 1 second, so I threaded it myself load of Form:

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

And my method UpdateStateis as follows:

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

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

Both methods within mine UpdateState are to update specific Abels, but since it is not the main thread that is updating the value of these Abels, it does not allow this to be done.

How can I update the value of these Abels using this thread to update their values?

2 answers

3


In windows, whoever "paints" the controls on the screen is the main message loop, in response to a windows event (WM_PAINT). That’s why you can’t update values in another thread’s controls.

Only the main thread redesigns the controls.

To circumvent this behavior, there is a "Invoke" method, in the "Control" class from which all visual controls are inherited. You can use this method to update the controls data.

Invoke method asks the main thread to update the value.

Follow the full reference of MSDN: http://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110). aspx

0

You should not use a normal thread to make changes to the Form. In this use Backgroundworker Class . In this link there is an example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.