创建定期工作项Create a periodic work item

重要的 ApiImportant APIs

了解如何创建定期重复的工作项。Learn how to create a work item that repeats periodically.

创建定期工作项Create the periodic work item

使用 CreatePeriodicTimer 方法创建定期工作项。Use the CreatePeriodicTimer method to create a periodic work item. 提供用于完成工作的 lambda,并使用 period 参数指定两次提交之间的间隔。Supply a lambda that accomplishes the work, and use the period parameter to specify the interval between submissions. 使用 TimeSpan 结构指定此期限。The period is specified using a TimeSpan structure. 每次在此期限到期时将重新提交工作项,因此请确保该期限足够长,以便完成工作。The work item will be resubmitted every time the period elapses, so make sure the period is long enough for work to complete.

CreateTimer 返回 ThreadPoolTimer 对象。CreateTimer returns a ThreadPoolTimer object. 存储该对象,以防需要取消计时器。Store this object in case the timer needs to be canceled.

请注意  避免指定的值为零 (或小于一毫秒的任何值) 的间隔。Note  Avoid specifying a value of zero (or any value less than one millisecond) for the interval. 这将导致定期计时器像单次计时器一样操作。This causes the periodic timer to behave as a single-shot timer instead.

请注意  可以使用 CoreDispatcher.RunAsync 访问 UI 并显示从工作项的进度。Note  You can use CoreDispatcher.RunAsync to access the UI and show progress from the work item.

以下示例创建每 60 秒运行一次的工作项:The following example creates a work item that runs once every 60 seconds:

TimeSpan period = TimeSpan.FromSeconds(60);

ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((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.
                //

            });

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

ThreadPoolTimer ^ PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer(
        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.
                    //
                        
                }));

        }), period);

处理定期工作项的取消(可选)Handle cancellation of the periodic work item (optional)

如果需要,可以使用 TimerDestroyedHandler 处理定期计时器的取消。If needed, you can handle cancellation of the periodic timer with a TimerDestroyedHandler. 使用 CreatePeriodicTimer 重载以提供用于处理定期工作项取消的其他 lambda。Use the CreatePeriodicTimer overload to supply an additional lambda that handles cancellation of the periodic work item.

以下示例创建每 60 秒重复一次的定期工作项,并且它还提供一个取消处理程序:The following example creates a periodic work item that repeats every 60 seconds and it also supplies a cancellation handler:

using Windows.System.Threading;

    TimeSpan period = TimeSpan.FromSeconds(60);

    ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((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.
                //

            });
    },
    period,
    (source) =>
    {
        //
        // TODO: Handle periodic timer cancellation.
        //

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

                // Periodic timer cancelled.

            }));
    });
using namespace Windows::System::Threading;
using namespace Windows::UI::Core;

TimeSpan period;
period.Duration = 60 * 10000000; // 10,000,000 ticks per second

ThreadPoolTimer ^ PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer(
        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.
                    //

                }));

        }),
        period,
        ref new TimerDestroyedHandler([&](ThreadPoolTimer ^ source)
        {
            //
            // TODO: Handle periodic timer cancellation.
            //

            Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([&]()
                {
                    //
                    // UI components can be accessed within this scope.
                    //

                    // Periodic timer cancelled.

                }));
        }));

取消计时器Cancel the timer

如有必要,调用 Cancel 方法停止定期工作项重复运行。When necessary, call the Cancel method to stop the periodic work item from repeating. 如果取消定期计时器时正在运行工作项,则允许完成该工作项。If the work item is running when the periodic timer is cancelled it is allowed to complete. 当定期工作项的所有实例完成时,请调用 TimerDestroyedHandler(如已提供)。The TimerDestroyedHandler (if provided) is called when all instances of the periodic work item have completed.

PeriodicTimer.Cancel();
PeriodicTimer->Cancel();

备注Remarks

有关一次性计时器的信息,请参阅使用计时器提交工作项For information about single-use timers, see Use a timer to submit a work item.