使用计时器提交工作项Use a timer to submit a work item

重要的 ApiImportant APIs

了解如何创建在经过计时器时间后运行的工作项。Learn how to create a work item that runs after a timer elapses.

创建单次计时器Create a single-shot timer

使用 CreateTimer 方法为工作项创建计时器。Use the CreateTimer method to create a timer for the work item. 提供用于完成工作的 lambda,并使用 delay 参数指定线程池在可将工作项分配给可用线程之前等待的时间。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. 使用 TimeSpan 结构指定延迟。The delay is specified using a TimeSpan structure.

请注意  可以使用 CoreDispatcher.RunAsync 访问 UI 并显示从工作项的进度。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);

提供完成处理程序Provide a completion handler

如果需要,使用 TimerDestroyedHandler 处理工作项的取消和完成。If needed, handle cancellation and completion of the work item with a TimerDestroyedHandler. 使用 CreateTimer 重载以提供其他 lambda。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.
                    }

                }));
        }));

取消计时器Cancel the timer

如果计时器仍在倒计时,但是已不再需要工作项,调用 CancelIf 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 平台 (UWP) 应用无法使用 Thread.Sleep,因为它会阻止 UI 线程。Universal Windows Platform (UWP) apps can't use Thread.Sleep because it can block the UI thread. 你可以改为使用 ThreadPoolTimer 创建工作项,这将延迟工作项完成的任务,但不会阻止 UI 线程。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. 原本针对 Windows 8.1 编写的代码示例,但代码可以在 Windows 10 中重复使用。The code sample was originally written for Windows 8.1 but the code can be re-used in Windows 10.

有关重复计时器的信息,请参阅创建定期工作项For information about repeating timers, see Create a periodic work item.