How to submit a work item using a timer (XAML)
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:
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:
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.
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.
Related topics
- 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