0

Windowsフォームでプログレスバーを使用しているときに問題が発生しました。ボタンのクリックで実行される10個の部分を持つアルゴリズムがあるとします。各パートの後で、フォームの進行状況バーをさらに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 に答える