WPF中UI線程隊列由Dispatcher來管理和調度,所以當使用者線程中更新UI時,必須通過Dispatche來調度,下面這個小例子將給使用者展示如何在使用者線程中更新當前的時間. 前台的XAML代碼如下:<Windowx:Class="ThreadInvoke.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ThreadInvoke"Height="300"Width="300" > <StackPanelOrientation="Vertical"> <StackPanelOrientation="Horizontal"> <ButtonContent="Ok"Click="okClick"Width="50"/> <ButtonContent="Stop"Click="stopClick"Width="50"/> </StackPanel> <TextBoxName="timeText"></TextBox> </StackPanel></Window> 背景主要代碼如下: //申明一個代理用於想UI更新時間private delegate void DelegateSetCurrentTime(); //申明一個變數,用於停止時間的跳動private bool stopFlag = false; //處理開始和結束事件private void okClick(object sender,RoutedEventArgs args) { stopFlag = false; Thread thread = new Thread(new ThreadStart(refreshTime)); thread.Start(); } private void stopClick(object sender, RoutedEventArgs args) { stopFlag = true; } //使用者線程的實現函數 private void refreshTime() { while (!stopFlag) {//向UI介面更新時鐘顯示 Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.SystemIdle, new DelegateSetCurrentTime(setCurrentTime)); } } private void setCurrentTime() { String currentTime = System.DateTime.Now.ToString(); timeText.Text = currentTime; } 2007-1-8 Paul.Peng