2

I have this Progress Bar class (Testing threading)

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

And then I'm calling all of it in a different class A to update the GUI from there:

ProgressBarUpdate updateBar = new ProgressBarUpdate();

        Thread currentProgressUpdater = new Thread(new ThreadStart(updateBar.DoCurUpdate));

        try
        {
            currentProgressUpdater.Start();

            currentProgressUpdater.Join();
        }
        catch (Exception)
        {

        }

And after I run it, I get the dialog where my application has stopped responding (right away) and then it asks me to close. Am I not implementing Threads correctly? Or am I missing a step?

4

2 回答 2

3

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

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

您还可以从新线程中运行的方法访问控件。那是行不通的。UI 控件只能从 UI 线程访问。

于 2013-05-16T15:05:51.510 回答
0

您在这里处于无限循环中while (!stopCur)

您从未设置stopCurtrue.

于 2013-05-16T15:05:14.440 回答