选框进度条有问题

本文关键字:有问题 | 更新日期: 2023-09-27 18:02:23

我正在学习使用线程,并做了一些多线程的演示。

我有一个名为lblText的标签和一个名为 pgbrown 的选框进度条。我做了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();
    }
}

选框进度条有问题

你应该使用微软的响应式框架。这会让事情变得容易得多。

代码如下:

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

选择"Rx-WinForms",并将其添加到您的项目中。

不清楚你想用进度条做什么。请介绍有关情况。

看完这篇非常有用的文章后,我发现#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;
}