Thread not updating progress bar control - C#

北城余情 提交于 2019-12-02 16:11:29

问题


I have a custom form with a custom progress bar, spawned in the main class(main thread). Then I spawn a thread and send it a ThreadStart function. This thread start function should update the progress bar in the custom control, but doesnt.:

class MyClass
{
......
//Custom form with progress bar
public CustomFormWithProgressBar statusScreen = new CustomFormWithProgressBar(0);
//thread to use
private Thread myThread;

.....
//Linked to a button to trigger the update procedure.
void ButtonPressEvent(.......)
{
    //create a sub thread to run the work and handle the UI updates to the progress bar
    myThread = new Thread(new ThreadStart(ThreadFunction));
    myThread.Start();
}
.....
//The function that gets called when the thread runs
public void ThreadFunction()
{
    //MyThreadClass myThreadClassObject = new MyThreadClass(this);
    //myThreadClassObject.Run();
    statusScreen.ShowStatusScreen();

    for (int i = 0; i < 100; i++ )
    {
        statusScreen .SetProgressPercentage(i);
        Thread.Sleep(20);
    }
    statusScreen.CloseStatusScreen();
}

Now my statusScreen form just sits and does nothing. No updates occur. But i have confirmed that the sub thread is indeed created and while i am in ThreadFunction, i am runnin on the new thread. Determined this through the Thread window in visual studio.

Why are my updates to the progress percentage of the status screen not being shown? How can i get my updates to push new values to the progress screen and have it show live?

Please note that the integer values being send into the status screen functions represent a percentage of completion. The Thread.Sleep is simply to see the updates if/when the happen.

Note this is not a re-drawing issue. i call Invalidate when the progress percentage is passed into the custom progress bar


回答1:


You can not update Controls from another thread.

The right way - is using BackgroundWorker for your purposes. Another way (almost right way) - use Control.Invoke method. And one more another almost right way - use SynchronizationContext.

But you may choose a dark side of power and use CheckForIllegalCrossThreadCalls - static property of Control class and set it to false.




回答2:


Since your progress bar is on the UI/Main thread, your thread cannot modify it without causing a cross thread reference exception. You should be invoking the action to the main thread.

Example:

// in your thread
this.Invoke((MethodInvoker)delegate {
    statusScreen.SetProgressPercentage(value); // runs on main thread
});


来源:https://stackoverflow.com/questions/16347008/thread-not-updating-progress-bar-control-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!