Usare un timer per inviare un elemento di lavoro

API importanti

Informazioni su come creare un elemento di lavoro che viene eseguito dopo la scadenza di un timer.

Creare un timer singolo

Utilizzare il metodo CreateTimer per creare un timer per l'elemento di lavoro. Specificare un'espressione lambda che esegue il lavoro e usare il parametro delay per specificare il tempo di attesa del pool di thread prima che possa assegnare l'elemento di lavoro a un thread disponibile. Il ritardo viene specificato utilizzando una struttura TimeSpan.

Nota È possibile usare CoreDispatcher.RunAsync per accedere all'interfaccia utente e mostrare lo stato di avanzamento dall'elemento di lavoro.

Nell'esempio seguente viene creato un elemento di lavoro eseguito in tre minuti:

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);

Fornire un gestore di completamento

Se necessario, gestire l'annullamento e il completamento dell'elemento di lavoro con TimerDestroyedHandler. Usare l'overload CreateTimer per fornire un'espressione lambda aggiuntiva. Viene eseguito quando il timer viene annullato o quando l'elemento di lavoro viene completato.

L'esempio seguente crea un timer che invia l'elemento di lavoro e chiama un metodo al termine dell'elemento di lavoro o il timer viene annullato:

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.
                    }

                }));
        }));

Annullare il timer

Se il timer continua a contare in basso, ma l'elemento di lavoro non è più necessario, chiamare Annulla. Il timer viene annullato e l'elemento di lavoro non verrà inviato al pool di thread.

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

Osservazioni:

app piattaforma UWP (Universal Windows Platform) (UWP) non possono usare Thread.Sleep perché può bloccare il thread dell'interfaccia utente. Si può usare un ThreadPoolTimer per creare invece un elemento di lavoro e questo ritarderà l'attività eseguita dall'elemento di lavoro senza bloccare il thread dell'interfaccia utente.

Vedere l'esempio di pool di thread per un esempio di codice completo che illustra gli elementi di lavoro, gli elementi di lavoro timer e gli elementi di lavoro periodici. L'esempio di codice è stato originariamente scritto per Windows 8.1, ma il codice può essere riutilizzato in Windows 10.

Per informazioni sui timer ripetuti, vedere Creare un elemento di lavoro periodico.