///做了一個wpf多線程,在實際場景中利用多線程保證程序不會卡死,性能上有所提高
//啟動線程處理
Thread thread1 = new Thread(UpdateBtn);
thread1.IsBackground = true;//設置為后台線程,當主線程結束后,后台線程自動退出,否則不會退出程序不能結束
thread1.Start();
private void UpdateBtn()
{
//做時name為datatable循環取值給前台txt追加
for (int i = 0; i < name.Rows.Count; i++)
{
Action action1 = () =>
{
this.txt.AppendText(name.Rows[i][0].ToString() + " ");
this.txt.AppendText(name.Rows[i][1].ToString() + " ");
this.txt.AppendText(name.Rows[i][2].ToString() + " ");
this.txt.AppendText(name.Rows[i][3].ToString() + " \r\n");
txt.Select(txt.Text.Length, 0);
Keyboard.Focus(txt);
};
//因為主線程在調用所以調用主線程上的委托
this.bfb.Dispatcher.Invoke(
new Action(
delegate
{
var s = Math.Round((float)i / name.Rows.Count * 100, 2) + "%";
this.bfb.Content = s;
}));
this.txt.Dispatcher.BeginInvoke(action1);
SetprogressBar(i);
// 如果不設置等待,會導致程序卡死
Thread.Sleep(50);
}
this.progressBar1.Dispatcher.Invoke(
new Action(
delegate
{
bol = true;
System.Windows.MessageBox.Show("執行完畢");
progressBar1.Visibility = Visibility.Hidden; //隱藏
bfb.Visibility = Visibility.Hidden; //隱藏
}));
}
附帶效果圖: