DispatcherTimer
是 WPF 中用于執行定時任務的類,用于在指定的時間間隔內執行任務。它與 UI 線程的 Dispatcher
相關聯,因此可以用來更新 UI 元素,而不必擔心線程安全問題。
關鍵特性:
- 線程安全:
DispatcherTimer
?確保在創建它的線程(通常是 UI 線程)上執行回調。 - 時間間隔:通過?
Interval
?屬性設置觸發回調的時間間隔。 - 啟動和停止:使用?
Start()
?和?Stop()
?方法來控制定時器。 - 一次性使用:如果只需要執行一次,可以使用?
Invoke
?或?BeginInvoke
?方法。
以下是如何在 WPF 應用程序中使用 DispatcherTimer
的基本步驟:
-
創建 DispatcherTimer 實例: 在你的代碼中(例如在 ViewModel 或代碼后臺中),創建
DispatcherTimer
的一個實例。 -
設置 Interval: 設置
DispatcherTimer
的Interval
屬性,這定義了觸發事件的時間間隔。 -
處理 Tick 事件: 訂閱
DispatcherTimer
的Tick
事件,并在事件處理程序中實現要執行的邏輯。 -
啟動和停止 Timer: 使用
DispatcherTimer
的Start
和Stop
方法來控制計時器的開始和結束。
?以下是一個簡單的示例,展示如何在 WPF 應用程序中使用 DispatcherTimer
:
ViewModel中:
public class F0ProcedureViewModel { public int _currentIndex = 0;public List<string> Items { get; set; } = new List<string>{ "Coarse search center frequency", "Initial F0 value:63470000","Fine search center frequency","check frequency 63470180","valid output parameter", "save parameter", "Calibration completed" };DispatcherTimer timer = new DispatcherTimer();public F0ProcedureViewModel(){timer.Tick += UpdateExecutionProgress;timer.Interval = TimeSpan.FromSeconds(1); //設置刷新的間隔時間UpdateExecutionProgress()}//掃描過程更新private void UpdateExecutionProgress(){if (_currentIndex < Items.Count){ProcessList.Add(Items[_currentIndex]); // 為當前索引的元素賦值_currentIndex++;}else{timer.Stop();}}}
xaml中:
<ItemsControl ItemsSource="{Binding ProcessList}"><ItemsControl.ItemTemplate><DataTemplate><!-- 綁定到數組的每個元素 --><TextBlock Text="{Binding }" Foreground="#fff" Margin="4"/></DataTemplate></ItemsControl.ItemTemplate>
</ItemsControl>
DispatcherTimer
是 WPF 應用程序中處理周期性任務的有用工具,特別是在需要與 UI 交互時。