詳細信息參考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元素,不會引發(fā)跨線程調用的異常.
構造函數(shù):
DispatcherTimer( ),
DispatcherTimer(DispatcherPriority),
DispatcherTimer(DispatcherPriority,Dispatcher),
?DispatcherTimer(TimeSpan, DispatcherPriority,Event Handler,Dispatcher)
屬性:Interval, IsEnable, Tag, Dispatcher
主要方法:Start( ),Stop( )
事件:Tick
測試代碼:

創(chuàng)建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(); ? ? ? ? }
本文使用 文章同步助手 同步