Compartir a través de


How to submit a work item using a timer (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Learn how to create a work item that runs after a timer elapses.

Technologies

Instructions

Step 1: Create a single-shot timer

Use the CreateTimer method to create a timer for the work item. Supply a lambda that accomplishes the work, and use the delay parameter to specify how long the thread pool waits before it can assign the work item to an available thread. The delay is specified using a TimeSpan structure.

Note  You can use CoreDispatcher.RunAsync to access the UI and show progress from the work item.

 

The following example creates a work item that runs in three minutes:

TimeSpan delay = TimeSpan.FromMinutes(3);
            
ThreadPoolTimer DelayTimer = ThreadPoolTimer.CreateTimer(
    (source) =>
    {
        // 
        // TODO: Work
        // 
        
        // 
        // Update the UI thread by using the UI core dispatcher.
        // 
        Dispatcher.RunAsync(
            CoreDispatcherPriority.High,
            () =>
            {
                // 
                // UI components can be accessed within this scope.
                // 

            });

    }, delay);
TimeSpan delay;
delay.Duration = 3 * 60 * 10000000; // 10,000,000 ticks per second

ThreadPoolTimer ^ DelayTimer = ThreadPoolTimer::CreateTimer(
        ref new TimerElapsedHandler([this](ThreadPoolTimer^ source)
        {
            // 
            // TODO: Work
            // 
            
            // 
            // Update the UI thread by using the UI core dispatcher.
            // 
            Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([this]()
                {
                    // 
                    // UI components can be accessed within this scope.
                    // 

                    ExampleUIUpdateMethod("Timer completed.");

                }));

        }), delay);

Step 2: Provide a completion handler

If needed, handle cancellation and completion of the work item with a TimerDestroyedHandler. Use the CreateTimer overload to supply an additional lambda. This runs when the timer is cancelled or when the work item completes.

The following example creates a timer that submits the work item, and calls a method when the work item finishes or the timer is cancelled:

TimeSpan delay = TimeSpan.FromMinutes(3);
            
bool completed = false;

ThreadPoolTimer DelayTimer = ThreadPoolTimer.CreateTimer(
    (source) =>
    {
        // 
        // TODO: Work
        // 

        // 
        // Update the UI thread by using the UI core dispatcher.
        // 
        Dispatcher.RunAsync(
                CoreDispatcherPriority.High,
                () =>
                {
                    // 
                    // UI components can be accessed within this scope.
                    // 

                });

        completed = true;
    },
    delay,
    (source) =>
    {
        // 
        // TODO: Handle work cancellation/completion.
        // 


        // 
        // Update the UI thread by using the UI core dispatcher.
        // 
        Dispatcher.RunAsync(
            CoreDispatcherPriority.High,
            () =>
            {
                // 
                // UI components can be accessed within this scope.
                // 

                if (completed)
                {
                    // Timer completed.
                }
                else
                {
                    // Timer cancelled.
                }

            });
    });
TimeSpan delay;
delay.Duration = 3 * 60 * 10000000; // 10,000,000 ticks per second

completed = false;

ThreadPoolTimer ^ DelayTimer = ThreadPoolTimer::CreateTimer(
        ref new TimerElapsedHandler([&](ThreadPoolTimer ^ source)
        {
            // 
            // TODO: Work
            // 

            // 
            // Update the UI thread by using the UI core dispatcher.
            // 
            Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([&]()
                {
                    // 
                    // UI components can be accessed within this scope.
                    // 

                }));

            completed = true;

        }),
        delay,
        ref new TimerDestroyedHandler([&](ThreadPoolTimer ^ source)
        {
            // 
            // TODO: Handle work cancellation/completion.
            // 

            Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([&]()
                {
                    // 
                    // Update the UI thread by using the UI core dispatcher.
                    // 

                    if (completed)
                    {
                        // Timer completed.
                    }
                    else
                    {
                        // Timer cancelled.
                    }

                }));
        }));

Step 3: Cancel the timer

If the timer is still counting down, but the work item is no longer needed, call Cancel. The timer is cancelled and the work item won't be submitted to the thread pool.

DelayTimer.Cancel();
DelayTimer->Cancel();

Remarks

Windows Runtime apps can't use Thread.Sleep because it can block the UI thread. You can use a ThreadPoolTimer to create a work item instead, and this will delay the task accomplished by the work item without blocking the UI thread.

See the thread pool sample for a complete code sample that demonstrates work items, timer work items, and periodic work items.

For information about repeating timers, see How to create a periodic work item.

Quickstart: Submitting a work item to the thread pool

How to create a periodic work item

How to create and use pre-allocated work items

How to respond to named events and semaphores

How to use functions as work item delegates

Best practices for using the thread pool