WPF學習筆記2——WPF子線程更新UI
1.Dispatcher
WPF應用程序的主線程負責創建UI界面、接收輸入、處理事件等任務,在開發中常用子線程處理一些耗時的操作(為了主線程能及時響應,防止假死),但是子線程是不能直接更新UI界面。Dispatcher的作用是管理線程工作項隊列,我們可以使用Dispatcher更新UI界面。
2.使用Dispatcher更新UI界面
下面是一個簡單的例子,在子線程直接更新主線程維護的界面。
using System;
using System.Threading; using System.Windows; namespace WpfApp1 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Thread thread = new Thread(ModifyLabel); lblShow.Content = "開始工作"; thread.Start(); } private void ModifyLabel() { // 模擬工作正在進行 Thread.Sleep(TimeSpan.FromSeconds(2)); lblShow.Content = "結束工作"; } } }
錯誤截圖:
在子線程中使用Dispatcher.BeginInvoke()方法更新UI。
using System;
using System.Threading; using System.Windows; namespace WpfApp1 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Thread thread = new Thread(ModifyLabel); lblShow.Content = "開始工作"; thread.Start(); } private void ModifyLabel() { // 模擬工作正在進行 Thread.Sleep(TimeSpan.FromSeconds(2)); //子線程更新UI線程可以使用Dispatcher.BeginInvoke()或者Invoke()方法。 this.Dispatcher.BeginInvoke(new Action(() => { //更新操作 lblShow.Content = "結束工作"; })); } } }
子線程更新UI可以使用Dispatcher.BeginInvoke()或者Invoke()方法,Dispatcher.Invoke()是同步執行