简体   繁体   中英

Threading: Setting checkbox's visibility

In a C#.NET windows application (winforms) I set the visibility of the checkbox to false:

checkBoxLaunch.Visible = true;

I started a thread.

Thread th = new Thread(new ThreadStart(PerformAction));
th.IsBackground = true;
th.Start();

The thread performs some stuff and sets the visibility to true:

private void PerformAction()
{
/*
.
.// some actions.
*/
    checkBoxLaunch.Visible = true;

}

After the thread finishes its task, the checkbox is not visible to me.

What am I missing?

You shouldn't make UI changes within a non-UI thread. Use Control.Invoke , Control.BeginInvoke or BackgroundWorker to marshal the call back to the UI thread. For example (assuming C# 3):

private void PerformAction()
{
/*
.
.// some actions.
*/
    MethodInvoker action = () => checkBoxLaunch.Visible = true;
    checkBoxLaunch.BeginInvoke(action);
}

Search for any of Control.Invoke, Control.BeginInvoke or BackgroundWorker to find hundreds of articles about this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM