线程未更新进度条控件-C# [英] Thread not updating progress bar control - C#

查看:174
本文介绍了线程未更新进度条控件-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自定义进度栏的自定义窗体,该窗体在主类(主线程)中生成.然后,我生成一个线程并向其发送ThreadStart函数.此线程启动功能应更新自定义控件中的进度条,但不更新.:

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();
}

现在,我的statusScreen表单可以放置并且不执行任何操作.没有更新发生.但是我已经确认确实创建了子线程,并且当我在ThreadFunction中时,我正在新线程上运行.通过Visual Studio中的线程"窗口确定了这一点.

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?

请注意,发送到状态屏幕功能的整数值表示完成百分比. Thread.Sleep只是在发生时查看更新.

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.

请注意,这不是重绘问题.当进度百分比传递到自定义进度栏中时,我称Invalidate

推荐答案

您不能从另一个线程更新控件.

You can not update Controls from another thread.

正确的方法-为您的目的使用BackgroundWorker. 另一种方法(几乎正确的方法)-使用Control.Invoke方法. 还有另一种几乎正确的方法-使用SynchronizationContext.

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.

但是您可以选择功能的阴暗面,并使用CheckForIllegalCrossThreadCalls-Control类的静态属性,并将其设置为false.

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

这篇关于线程未更新进度条控件-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆