跑马灯进度条有问题

Something wrong with Marquee progress bar

我正在学习使用线程并制作一些多线程演示。

我有一个名为 lblText 的标签和一个名为 pgbRun 的字幕进度条。我制作了 2 个线程,一个让标签的文本在每次 Thread.Sleep() 调用后发生变化,另一个让进度条在标签的文本发生变化时显示动画。

我遇到的问题是文本更改线程似乎运行良好,但进度条线程有问题。 pgbRun 在文本更改完成后才开始动画。

请帮我找出我的代码有什么问题,并告诉我一些修复它的方法。非常感谢!

private delegate void formDelegate();

private void btnRun_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(new ThreadStart(new formDelegate(textChange)));
    thread.IsBackground = true;
    thread.Start();
}

public void textChange()
{
    if (lblText.InvokeRequired)
    {
        lblText.BeginInvoke(new formDelegate(textChange));
    }
    else
    {
        Thread thread = new Thread(new ThreadStart(new formDelegate(progess))); 
        thread.IsBackground = true;
        thread.Start();

        //I try make single thread that config progress bar here but i have same trouble.

        for (int i = 0; i < 10; i++)
        {
            lblText.Text = "Count: " + i;
            lblText.Update();
            lblText.Refresh();
            Thread.Sleep(300);
        }
    }
}

public void progess()
{
    if (pgbRun.InvokeRequired)
    {
        pgbRun.BeginInvoke(new formDelegate(progess));
    }
    else
    {
        pgbRun.Style = ProgressBarStyle.Marquee;
        pgbRun.MarqueeAnimationSpeed = 20;
        pgbRun.Update();
        pgbRun.Refresh();
    }
}

读完this very useful article,我发现#Hans 很真实。我的第一个代码是垃圾,所以我按如下方式编辑我的代码。进度条的基本属性在设计器中设置,在代码中我只是更改可见选项。

delegate void textChangeDelegate(int x);

private void btnRun_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(new ThreadStart(new MethodInvoker(threadJob)));
    thread.IsBackground = true;
    thread.Start();
}

public void threadJob()
{
    Invoke(new MethodInvoker(show));
    for (int i = 0; i < 10; i++)
    {
        Invoke(new textChangeDelegate(textChange),new object[]{i});
        Thread.Sleep(500);
    }
    Invoke(new MethodInvoker(hide));
}

public void textChange(int x)
{
    if (InvokeRequired)
    {
        BeginInvoke(new textChangeDelegate(textChange),new object[] {x});
        return;
    }
    x += 1;
    lblText.Text = "Count: " + x;
}

public void show()
{
    pgbRun.Visible = true;
    lblText.Visible = true;
}

public void hide()
{
    pgbRun.Visible = false;
    lblText.Text = "";
    lblText.Visible = false;
}

您应该为此使用 Microsoft 的 Reactive Framework。它会让事情变得容易得多。

代码如下:

private void btnRun_Click(object sender, EventArgs e)
{
    Observable
        .Interval(TimeSpan.FromMilliseconds(300.0))
        .Take(10)
        .Select(n => String.Format("Count: {0}", n))
        .ObserveOn(this)
        .Subscribe(t => lbl.Text = t);
}

就是这样。

只需 NuGet "Rx-WinForms" 并将其添加到您的项目中。

不清楚您要用进度条做什么。您能否提供更多详细信息?