如何使用的WinForms进度条? [英] How to use WinForms progress bar?
问题描述
我要显示的计算,这是在执行外部库的进度。
I want to show progress of calculations, which are performing in external library.
例如,如果我有一些计算方法,我想在我的Form类使用它为100000值我可以这样写:
For example if I have some calculate method, and I want to use it for 100000 values in my Form class I can write:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Caluculate(int i)
{
double pow = Math.Pow(i, i);
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100000;
progressBar1.Step = 1;
for(int j = 0; j < 100000; j++)
{
Caluculate(j);
progressBar1.PerformStep();
}
}
}
我应该执行每次计算后一步。但如果我执行外部方法的所有计算100000。当我应该执行步骤如果我不想让这种方法依赖进度条?我可以,例如,写
I should perform step after each calculation. But what if I perform all 100000 calculations in external method. When should I "perform step" if I don't want to make this method dependant on progress bar? I can, for example, write
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CaluculateAll(System.Windows.Forms.ProgressBar progressBar)
{
progressBar.Maximum = 100000;
progressBar.Step = 1;
for(int j = 0; j < 100000; j++)
{
double pow = Math.Pow(j, j); //Calculation
progressBar.PerformStep();
}
}
private void button1_Click(object sender, EventArgs e)
{
CaluculateAll(progressBar1);
}
}
但我不想做这样的。
but I don't want to do like that.
推荐答案
我建议你看看<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\">BackgroundWorker.如果你有一个循环,在大的WinForm的它会阻止你的应用程序看起来像它已吊死。
I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.
看 BackgroundWorker.ReportProgress()
来看看如何报告进度回UI线程。
Look at BackgroundWorker.ReportProgress()
to see how to report progress back to the UI thread.
例如:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
progressBar1.Value = 0;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var backgroundWorker = sender as BackgroundWorker;
for (int j = 0; j < 100000; j++)
{
Calculate(j);
backgroundWorker.ReportProgress((j * 100) / 100000);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// TODO: do something with final calculation.
}
这篇关于如何使用的WinForms进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!