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 交互时。