2013年4月16日 星期二
C# UI update thread backgroundWorker
運算要放在UI thread之外,才不會卡到UI呈現
這裡介紹用backgroundWorker的方式
step1.
using System.ComponentModel.BackgroundWorker;
step2.
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
step3.
public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//在此放你要的運算
String xxx=運算的結果();
//呼叫UI狀態的改變
backgroundWorker.ReportProgress(0, xxx);
}
private void backgroundWorker_ProgressChanged(object sender,ProgressChangedEventArgs e)
{
//UI的改變放在這
msg.Text += e.UserState.ToString();
msg.ScrollToEnd();
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//全部做完時
msg.Text += "\ncompleted ";
msg.ScrollToEnd();
}
step4.
private void button2_Click(object sender, RoutedEventArgs e){
msg.Text = "start analysis....\n";
//啟動backgroundworker
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.RunWorkerAsync();
}
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言