【问题标题】:Updating Windows Forms GUI while code is running在代码运行时更新 Windows 窗体 GUI
【发布时间】:2012-11-24 04:25:05
【问题描述】:

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

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

【问题讨论】:

  • 我先看看 BackgroundWorker 类。
  • MSDN 是你的朋友。 BackgroundWorker 类的文档是一个很好的起点。 msdn.microsoft.com/en-us/library/…
  • 线程也是不错的起点。

标签: c# .net progress-bar


【解决方案1】:

您需要使用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++
  }));
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      相关资源
      最近更新 更多