[英]Updating Windows Forms GUI while code is running
I've run into some problems while using progress bars in Windows Forms. 在Windows窗体中使用进度栏时遇到了一些问题。 Say I have an algorithm with ten parts that runs on a button click.
假设我有一个包含十个部分的算法,只需单击一下按钮即可运行。 After each part, I'd want to update a progress bar on the form to 10% further along.
在每个部分之后,我想将表单上的进度条更新为10%。 However, when code is running, the Windows Form will not respond or update.
但是,在运行代码时,Windows窗体将不会响应或更新。
What is the correct do show progress on a form while code is running? 在代码运行时,在表单上显示进度的正确方法是什么?
You need to use a BackgroundWorker
. 您需要使用
BackgroundWorker
。
A nice example can be found here: http://www.dotnetperls.com/progressbar 一个很好的例子可以在这里找到: 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();
}
}
}
Or you can use something like: 或者,您可以使用类似:
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++
}));
}
我建议将TPL用于更标准化,轻便,健壮和可扩展的操作,例如,参见: http : //blogs.msdn.com/b/pfxteam/archive/2010/10/15/10076552.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.