在使用DispatcherTimer之前,需要使用using System.Windows.Threading;命名空間;集成到按指定時間間隔和指定優先級處理的 Dispatcher 隊列中的計時器。 在每個 Dispatcher 循環的頂端重新計算 DispatcherTimer。 不能保證會正好在時間間隔發生時執行計時器,但能夠保證不會在時間間隔發生之前執行計時器。 這是因為 DispatcherTimer 操作與其他操作一樣被放置到 Dispatcher 隊列中。 何時執行 DispatcherTimer 操作取決於隊列中的其他作業及其優先級。在使用時代碼如下:
public Pachertime() { InitializeComponent(); DispatcherTimer time = new DispatcherTimer(); time.Interval = new TimeSpan(0, 0, 1); time.Tick += new EventHandler(time_Tick); time.Start(); } void time_Tick(object sender, EventArgs e) { tbkTimer.Text = "當前時間:" + DateTime.Now.ToLongTimeString(); }
主要代碼如上,則在客戶端可以看到一個在不斷更新的時間;DispatchTimer主要適合於調度任務的情況。事實上,除StoryBoard組件之外dispatcherTimer也是Silverlight編程中實現動畫效果的一種重要技術。當然,我們應該當心使用dispatcherTimer有可能導致創建太多的后台線程,從而有可能導致增加CPU的負荷而降低效率。
Dispatcher同樣的需要使用using System.Windows.Threading命名空間;Dispatcher 類當前只提供從非用戶界面 (UI) 線程在 UI 上運行代碼的支持。 您可以通過 DependencyObject . Dispatcher 和 ScriptObject . Dispatcher 屬性訪問 UI 線程的 Dispatcher 對象。這些方法是實例方法,但這些類型的實例無法頻繁從非 UI 線程訪問。
下面是一個實現倒計時功能的例子:
前台XAMl代碼:
<UserControl x:Class="slStudy.Timer" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <StackPanel x:Name="layerout" > <Border x:Name="border" Background="AliceBlue" Width="200" Height="50" Margin="5" BorderBrush="Black" BorderThickness="3" CornerRadius="5"></Border> <StackPanel Margin="80 0 0 0" Orientation="Horizontal" Width="188"> <Button Content="開始" x:Name="btnStart" Width="66" Height="30" Margin="5" Click="btnStart_Click"></Button> <Button Content="延遲" x:Name="btnJoin" Width="100" Height="30" Margin="5" Click="btnJoin_Click"></Button> </StackPanel> </StackPanel> </UserControl>
后台C#代碼如下:
public partial class Timer : UserControl { private static System.Windows.Controls.TextBlock tbk; private Thread thread; public Timer() { InitializeComponent(); tbk = new TextBlock() { FontSize = 15, Width = 300, Height = 100, }; border.Child = tbk; thread = new Thread(Timer.SetText); } public static void SetText() { int i = 60; while (i > 0) { tbk.Dispatcher.BeginInvoke(delegate() { tbk.Text = "倒計時:" + i + "秒"; }); i--; Thread.Sleep(1000); } } private void btnStart_Click(object sender, RoutedEventArgs e) { thread.Start(); } private void btnJoin_Click(object sender, RoutedEventArgs e) { thread.Join(2000); } }