详细信息参考MSDN:DispatcherTimer Class (System.Windows.Threading) | Microsoft Docs
Namespace:
Assembly: WindowsBase.dll
A timer that is integrated into the Dispatcher queue which is processed at a specified interval of time and at a specified priority.
运行在UI线程上的定时器,可以直接更新UI元素,不会引发跨线程调用的异常.
构造函数:
DispatcherTimer( ),
DispatcherTimer(DispatcherPriority),
DispatcherTimer(DispatcherPriority,Dispatcher),
DispatcherTimer(TimeSpan, DispatcherPriority,Event Handler,Dispatcher)
属性:Interval, IsEnable, Tag, Dispatcher
主要方法:Start( ),Stop( )
事件:Tick
测试代码:
创建2个DispatchTimer对象更新UI,显示当前时间
前台代码:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions> <Label Grid.Row="0 " Margin="5" FontWeight="ExtraBlack" x:Name="lblMsg">Test</Label>
<TextBlock Grid.Row="1" Margin="5" FontWeight="ExtraBlack" HorizontalAlignment="Center" x:Name="txtMsg">Test Text</TextBlock>
</Grid>
后台代码:
DispatcherTimer t1; DispatcherTimer t2;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
t1 = new DispatcherTimer();
t1.Tick += T1_Tick;
t1.Interval = new TimeSpan(0, 0, 1); t1.Start();
t2 = new DispatcherTimer();
t2.Tick += T2_Tick;
t2.Interval = TimeSpan.FromSeconds(1); t2.Start();
}
private void T2_Tick(object sender, EventArgs e)
{
txtMsg.Text = DateTime.Now.ToString("G");
// DateTime.Now.ToString("HH:mm:ss.fff"); }
private void T1_Tick(object sender, EventArgs e)
{
lblMsg.Content = DateTime.Now.Second;
CommandManager.InvalidateRequerySuggested(); }
本文使用 文章同步助手 同步