0

我在 Windows 窗体中使用进度条时遇到了一些问题。假设我有一个包含十个部分的算法,只需单击一下按钮即可运行。在每个部分之后,我想将表单上的进度条更新为 10%。但是,当代码运行时,Windows 窗体将不会响应或更新。

代码运行时在表单上显示进度的正确方法是什么?

4

2 回答 2

4

您需要使用BackgroundWorker.
一个很好的例子可以在这里找到:http: //www.dotnetperls.com/progressbar

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
    InitializeComponent();
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {
      // Start the BackgroundWorker.
      backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
      for (int i = 1; i <= 100; i++)
      {
        // Wait 100 milliseconds.
        Thread.Sleep(100);
        // Report progress.
        backgroundWorker1.ReportProgress(i);
      }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
      // Change the value of the ProgressBar to the BackgroundWorker progress.
      progressBar1.Value = e.ProgressPercentage;
      // Set the text.
      this.Text = e.ProgressPercentage.ToString();
    }
  }
}

或者你可以使用类似的东西:

private void StartButtonClick(object sender, EventArgs e)
{
    var t1 = new Thread(() => ProgressBar(value));
    t1.Start();
}

private void ProgressBar(value1)
{
  ProgressBar.BeginInvoke(new MethodInvoker(delegate
  {
      ProgresBar.Value++
  }));
}
于 2012-11-23T18:44:06.750 回答
0

我建议将 TPL 用于更标准化、轻量级、健壮和可扩展的操作,例如参见:http: //blogs.msdn.com/b/pfxteam/archive/2010/10/15/10076552.aspx

于 2012-11-23T20:25:05.687 回答