Share via


DispatcherTimer Class

Definition

Provides a timer that is integrated into the Dispatcher queue, which is processed at a specified interval of time and at a specified priority.

/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class DispatcherTimer
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public class DispatcherTimer
Public Class DispatcherTimer
Inheritance
Object IInspectable DispatcherTimer
Attributes

Windows requirements

Device family
Windows 10 (introduced in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v1.0)

Examples

This example code implements a simple console-style timer that writes data to a TextBlock named TimerLog (XAML that defines TimerLog is not shown). The Interval value is set to 1, and the log displays the actual elapsed time for each Tick.

DispatcherTimer dispatcherTimer;
DateTimeOffset startTime;
DateTimeOffset lastTime;
DateTimeOffset stopTime;
int timesTicked = 1;
int timesToTick = 10;

public void DispatcherTimerSetup()
{
    dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += dispatcherTimer_Tick;
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    //IsEnabled defaults to false
    TimerLog.Text += "dispatcherTimer.IsEnabled = " + dispatcherTimer.IsEnabled + "\n";
    startTime = DateTimeOffset.Now;
    lastTime = startTime;
    TimerLog.Text += "Calling dispatcherTimer.Start()\n";
    dispatcherTimer.Start();
    //IsEnabled should now be true after calling start
    TimerLog.Text += "dispatcherTimer.IsEnabled = " + dispatcherTimer.IsEnabled + "\n";
}

void dispatcherTimer_Tick(object sender, object e)
{
    DateTimeOffset time = DateTimeOffset.Now;
    TimeSpan span = time - lastTime;
    lastTime = time;
    //Time since last tick should be very very close to Interval
    TimerLog.Text += timesTicked + "\t time since last tick: " + span.ToString() + "\n";
    timesTicked++;
    if (timesTicked > timesToTick)
    {
        stopTime = time;
        TimerLog.Text += "Calling dispatcherTimer.Stop()\n";
        dispatcherTimer.Stop();
        //IsEnabled should now be false after calling stop
        TimerLog.Text += "dispatcherTimer.IsEnabled = " + dispatcherTimer.IsEnabled + "\n";
        span = stopTime - startTime;
        TimerLog.Text += "Total Time Start-Stop: " + span.ToString() + "\n";
    }
}
private void Page_Loaded_1(object sender, RoutedEventArgs e)
{
    DispatcherTimerSetup();
}
// MainPage.cpp
...
#include <chrono>
...
void MainPage::StartTimerAndRegisterHandler()
{
    Windows::UI::Xaml::DispatcherTimer timer;
    timer.Interval(std::chrono::milliseconds{ 500 });
    auto registrationtoken = timer.Tick({this, &MainPage::OnTick });
    timer.Start();
}

void MainPage::OnTick(Windows::Foundation::IInspectable const& /* sender */,
    Windows::Foundation::IInspectable const& /* e */)
{
    // do something on each tick here ...
}
// .cpp definition, .h not shown
void MainPage::StartTimerAndRegisterHandler() {
    auto timer = ref new Windows::UI::Xaml::DispatcherTimer();
    TimeSpan ts;
    ts.Duration = 500;
    timer->Interval = ts;
    timer->Start();
    auto registrationtoken = timer->Tick += ref new EventHandler<Object^>(this,&MainPage::OnTick);
}
void MainPage::OnTick(Object^ sender, Object^ e) {
    // do something on each tick here ...
}

Remarks

The DispatcherTimer can be used to run code on the same thread that produces the UI thread. Code running on this thread has the privilege to create and modify objects that can only be created and modified on the UI thread. To specify that code should run on the UI thread, set the Interval property and then call the Start method. The Tick event fires after the time specified in Interval has elapsed. Tick continues firing at the same Interval until the Stop method is called, the app terminates, or the app is suspended (fires Suspending).

One scenario for DispatcherTimer is to check properties on sensors where changes to the sensor values are not purely event-driven, or the events don't give you the granularity you want. You can see this in the Accelerometer sample.

Other scenarios for DispatcherTimer include checking for state changes that don't have related events, or for periodic UI updates that can't use a storyboarded animation or a two-way binding.

Tip

If you're migrating Microsoft Silverlight or Windows Presentation Foundation (WPF) code, the DispatcherTimer and the related Dispatcher was in a separate System.Windows.Threading namespace. There is no Windows.UI.Xaml.Threading namespace in the Windows Runtime, so this class is in Windows.UI.Xaml.

If you aren't doing anything with the UI thread in your Tick handlers and just need a timer, you could also use ThreadPoolTimer instead. Also, for techniques like ThreadPoolTimer or a .NET Task, you aren't totally isolated from the UI thread. You could still assign to the UI thread asynchronously using CoreDispatcher.RunAsync.

Constructors

DispatcherTimer()

Initializes a new instance of the DispatcherTimer class.

Properties

Interval

Gets or sets the amount of time between timer ticks.

IsEnabled

Gets a value that indicates whether the timer is running.

Methods

Start()

Starts the DispatcherTimer.

Stop()

Stops the DispatcherTimer.

Events

Tick

Occurs when the timer interval has elapsed.

Applies to

See also