///做了一个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; //隐藏
}));
}
附带效果图:
原文地址:https://www.cnblogs.com/ms1976/p/8618636.html