Menggunakan timer untuk mengirimkan item kerja

API Penting

Pelajari cara membuat item kerja yang berjalan setelah timer berlalu.

Membuat timer satu bidikan

Gunakan metode CreateTimer untuk membuat timer untuk item kerja. Berikan lambda yang melakukan tugas tersebut, dan gunakan parameter delay untuk menentukan berapa lama kumpulan utas menunggu sebelum dapat menugaskan item kerja ke utas yang tersedia. Penundaan ditentukan menggunakan struktur TimeSpan .

Note

Di aplikasi WinUI 3, gunakan DispatcherQueue.TryEnqueue dari Microsoft.UI.Dispatching.DispatcherQueue untuk mengakses utas UI dan tampilkan kemajuan dari item kerja. Lihat gambaran umum DispatcherQueue untuk detailnya.

Contoh berikut membuat item kerja yang berjalan dalam tiga menit:

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

Menyediakan handler penyelesaian

Jika diperlukan, tangani pembatalan dan penyelesaian item kerja dengan TimerDestroyedHandler. Gunakan kelebihan beban CreateTimer untuk menyediakan lambda tambahan. Ini berjalan ketika timer dibatalkan atau ketika item kerja selesai.

Contoh berikut membuat timer yang mengirimkan item kerja, dan memanggil metode saat item kerja selesai atau timer dibatalkan:

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

                }));
        }));

Batalkan pengatur waktu

Jika timer masih menghitung mundur, tetapi item kerja tidak lagi diperlukan, panggil Batal. Timer dibatalkan dan item kerja tidak akan diserahkan ke pool thread.

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

Komentar

Aplikasi Windows harus menghindari Thread.Sleep karena memblokir utas pemanggil, yang dapat membuat UI tidak responsif jika dipanggil pada utas UI. Anda dapat menggunakan ThreadPoolTimer untuk membuat item kerja sebagai gantinya, dan ini akan menunda tugas yang dicapai oleh item kerja tanpa memblokir utas UI.

Lihat contoh thread pool untuk contoh kode lengkap yang mendemonstrasikan item kerja, item kerja berbasis timer, dan item kerja berkala. Sampel kode awalnya ditulis untuk Windows 8.1 tetapi kode dapat digunakan kembali dalam Windows 10.

Untuk informasi tentang pengulangan timer, lihat Membuat item kerja berkala.