我想在带有字幕样式的表单上添加一个ProgressBar,以向用户显示正在进行的操作。在耗时的操作中,表单不会更新,因此ProgressBar也会“冻结”。

我检查了几篇有关BackgroundWorker的帖子,但就我而言,该操作未报告进度,因此这是我需要选取框的原因。

任何帮助或代码段表示赞赏。

注意:我需要使用.NET 4.0(用于XP支持),所以不能使用Task.Run :(

button1_Click(object sender, EventArgs e)
{
    progressBar1.Style = ProgressBarStyle.Marquee;
    progressBar1.MarqueeAnimationSpeed = 50;

    // INSERT TIME CONSUMING OPERATIONS HERE
    // THAT DON'T REPORT PROGRESS
    Thread.Sleep(10000);

    progressBar1.MarqueeAnimationSpeed = 0;
    progressBar1.Style = ProgressBarStyle.Blocks;
    progressBar1.Value = progressBar1.Minimum;

}

最佳答案

我检查了一些有关BackgroundWorker的帖子,但就我而言,
  操作不会报告进度,这就是为什么我需要选取框的原因。


您可以使用BackgroundWorker,只是不使用它的“进度”部分。这两件事并不互斥...

例:

    private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
        progressBar1.Style = ProgressBarStyle.Marquee;
        progressBar1.MarqueeAnimationSpeed = 50;

        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += bw_DoWork;
        bw.RunWorkerCompleted += bw_RunWorkerCompleted;
        bw.RunWorkerAsync();
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        // INSERT TIME CONSUMING OPERATIONS HERE
        // THAT DON'T REPORT PROGRESS
        Thread.Sleep(10000);
    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        progressBar1.MarqueeAnimationSpeed = 0;
        progressBar1.Style = ProgressBarStyle.Blocks;
        progressBar1.Value = progressBar1.Minimum;

        button1.Enabled = true;
        MessageBox.Show("Done!");
    }

10-06 05:07
查看更多