Share via


타이머를 사용하여 작업 항목 제출

중요 API

타이머가 경과한 후 실행되는 작업 항목을 만드는 방법을 알아봅니다.

일회용 타이머 생성

CreateTimer 메서드를 사용하여 작업 항목에 대한 타이머를 만듭니다. 작업을 완수하는 람다를 제공하고 delay 매개 변수를 사용, 스레드 풀이 사용 가능한 스레드에 작업 항목을 할당하기 전에 대기하는 시간을 지정합니다. 기간은 TimeSpan 구조를 사용하여 설정 됩니다.

참고, CoreDispatcher.RunAsync를 사용하여 UI에 액세스하고 작업 항목의 진행률을 표시할 수 있습니다.

다음 예제에서는 3분 후 실행되는 작업 항목을 만듭니다.

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

완료 처리기 제공

필요시 TimerDestroyedHandler 를 사용하여 작업 항목의 취소 및 완료를 처리합니다. CreateTimer 오버로드를 사용, 추가 람다를 제공합니다. 이는 타이머가 취소되거나 작업 항목이 완료될 때 실행됩니다.

다음 예제에서는 작업 항목을 제출하고 작업 항목이 완료되거나 타이머가 취소될 때 메서드를 호출하는 타이머를 만듭니다.

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 을 호출합니다. 타이머가 취소되고 작업 항목이 스레드 풀에 제출되지 않습니다.

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

설명

UI 스레드를 차단할 수 있기 때문에 UWP(유니버설 Windows 플랫폼) 앱은 Thread.Sleep를 사용할 수 없습니다. 대신 ThreadPoolTimer 를 사용하여 작업 항목을 만들 수 있으며, 작업 완료된 태스크가 지연되어 UI 스레드를 차단하지 않습니다.

작업 항목, 타이머 작업 항목, 그리고 정기 작업 항목을 설명하는 전체 코드 샘플을 보려면 스레드 풀 샘플 을 참조하세요. 코드 샘플은 본래 Windows 8.1용으로 작성되었지만 Windows 10에서 다시 사용할 수 있습니다.

반복 타이머에 대한 자세한 내용은 주기적 작업 항목 생성 을 참조하세요.