进度条和线程

本文关键字:线程 | 更新日期: 2023-09-27 18:13:50

我有这个进度条类(测试线程)

public class ProgressBarUpdate
    {
        //Add getters and setters
        static MainGUI theForm = (MainGUI)Application.OpenForms[0];
        ProgressBar pBarCur = theForm.pBarCur; //Yes, accessing public for now
        bool updateCur = false;
        bool stopCur = false;
        bool showMax = false;
    public ProgressBarUpdate()
    {
    }
    public void resetCur()
    {
        pBarCur.Value = 0;
    }
    public void DoCurUpdate()
    {
        while (!stopCur)
        {
            if (pBarCur.Value < (pBarCur.Maximum / 10) * 9)
                pBarCur.PerformStep();
            if (showMax)
            {
                pBarCur.Value = pBarCur.Maximum;
                showMax = false;
            }
        }
    }
public void StopCur()
        {
            stopCur = true;
        }
        public void UpdateCur()
        {
            updateCur = true;
        }
        public void UpdateToMax()
        {
            showMax = true;
        }

然后我在不同的类a中调用所有这些来从那里更新GUI:

ProgressBarUpdate updateBar = new ProgressBarUpdate();
        Thread currentProgressUpdater = new Thread(new ThreadStart(updateBar.DoCurUpdate));
        try
        {
            currentProgressUpdater.Start();
            currentProgressUpdater.Join();
        }
        catch (Exception)
        {
        }

在我运行它之后,我得到我的应用程序已经停止响应的对话框(马上),然后它要求我关闭。我没有正确实现线程吗?还是我漏了一步?

进度条和线程

您的问题是调用currentProgressUpdater.Join();。你正在阻塞UI线程。

创建一个新线程的全部意义在于允许UI线程继续处理UI事件。你不能让它这么做。启动一个线程,然后立即加入它,这与仅仅执行一行代码没有什么不同。

你还从新线程中运行的方法访问控件。这行不通。UI控件只能从UI线程访问。

这是一个无限循环while (!stopCur)

您从未将stopCur设置为true