异步更新UI的几种方法
①.使用Control.Invoke方式来更新数据
foreach (DataGridViewRow dgvr in this.dgv_selected.Rows)
{
Application.DoEvents();
this.progressBar1.Invoke(new MethodInvoker(delegate { this.progressBar1.Maximum = this.dgv_selected.Rows.Count; }));
//this.progressBar1.Invoke(new MethodInvoker(delegate { this.label12.Text = "正在保存:" + dgvr.Cells["Column3"].Value.ToString(); }));
this.label12.Invoke(new MethodInvoker(delegate { this.label12.Text = "操作进度:" + dgvr.Cells["Column3"].Value.ToString(); }));
this.label12.Refresh();
this.progressBar1.Invoke(new MethodInvoker(delegate { this.progressBar1.Value++; }));
}
②.使用委托来更新:
private delegate void IncreaseProgressBarValue(string username);
private void updateProgerssBar(string username)
{
if (this.progressBar1.InvokeRequired)
{
IncreaseProgressBarValue inc = new IncreaseProgressBarValue(updateProgerssBar);
this.progressBar1.Invoke(inc,new object[]{username});
}
else
{
this.progressBar1.Value++;
this.label12.Text = "查询员工:" + username;
this.label12.Refresh();
}
}
使用下面的方式调用委托:
ThreadStart ts = delegate { updateProgerssBar(dgvr.Cells["EmpName"].Value.ToString()); };
new Thread(ts).Start();
③.在.net framework4.0中使用TaskScheduler来实时更新UI
private void AsyncWork()
{
// This scheduler will execute tasks
// on the current SynchronizationContext
// That is, it will access UI controls safely
var uis = TaskScheduler.FromCurrentSynchronizationContext();
for (int i = 0; i < 100; i++)
{
Application.DoEvents();
Task.Factory.StartNew(() =>
{
updateProgressBar();
}, new CancellationToken(), TaskCreationOptions.None, uis);
}
}
private void updateProgressBar()
{
this.progressBar1.Value++;
Thread.Sleep(100);
}