DispatcherTimer 클래스

정의

지정된 시간 간격 및 지정된 우선 순위로 처리되는 Dispatcher 큐에 통합된 타이머를 제공합니다.

/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class DispatcherTimer
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public class DispatcherTimer
Public Class DispatcherTimer
상속
Object IInspectable DispatcherTimer
특성

Windows 요구 사항

디바이스 패밀리
Windows 10 (10.0.10240.0에서 도입되었습니다.)
API contract
Windows.Foundation.UniversalApiContract (v1.0에서 도입되었습니다.)

예제

이 예제 코드는 라는 TimerLogTextBlock에 데이터를 쓰는 간단한 콘솔 스타일 타이머를 구현합니다TimerLog(정의하는 XAML은 표시되지 않음). Interval 값은 1로 설정되고 로그는 각 에 대한 실제 경과 시간을 표시합니다.

DispatcherTimer dispatcherTimer;
DateTimeOffset startTime;
DateTimeOffset lastTime;
DateTimeOffset stopTime;
int timesTicked = 1;
int timesToTick = 10;

public void DispatcherTimerSetup()
{
    dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += dispatcherTimer_Tick;
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    //IsEnabled defaults to false
    TimerLog.Text += "dispatcherTimer.IsEnabled = " + dispatcherTimer.IsEnabled + "\n";
    startTime = DateTimeOffset.Now;
    lastTime = startTime;
    TimerLog.Text += "Calling dispatcherTimer.Start()\n";
    dispatcherTimer.Start();
    //IsEnabled should now be true after calling start
    TimerLog.Text += "dispatcherTimer.IsEnabled = " + dispatcherTimer.IsEnabled + "\n";
}

void dispatcherTimer_Tick(object sender, object e)
{
    DateTimeOffset time = DateTimeOffset.Now;
    TimeSpan span = time - lastTime;
    lastTime = time;
    //Time since last tick should be very very close to Interval
    TimerLog.Text += timesTicked + "\t time since last tick: " + span.ToString() + "\n";
    timesTicked++;
    if (timesTicked > timesToTick)
    {
        stopTime = time;
        TimerLog.Text += "Calling dispatcherTimer.Stop()\n";
        dispatcherTimer.Stop();
        //IsEnabled should now be false after calling stop
        TimerLog.Text += "dispatcherTimer.IsEnabled = " + dispatcherTimer.IsEnabled + "\n";
        span = stopTime - startTime;
        TimerLog.Text += "Total Time Start-Stop: " + span.ToString() + "\n";
    }
}
private void Page_Loaded_1(object sender, RoutedEventArgs e)
{
    DispatcherTimerSetup();
}
// MainPage.cpp
...
#include <chrono>
...
void MainPage::StartTimerAndRegisterHandler()
{
    Windows::UI::Xaml::DispatcherTimer timer;
    timer.Interval(std::chrono::milliseconds{ 500 });
    auto registrationtoken = timer.Tick({this, &MainPage::OnTick });
    timer.Start();
}

void MainPage::OnTick(Windows::Foundation::IInspectable const& /* sender */,
    Windows::Foundation::IInspectable const& /* e */)
{
    // do something on each tick here ...
}
// .cpp definition, .h not shown
void MainPage::StartTimerAndRegisterHandler() {
    auto timer = ref new Windows::UI::Xaml::DispatcherTimer();
    TimeSpan ts;
    ts.Duration = 500;
    timer->Interval = ts;
    timer->Start();
    auto registrationtoken = timer->Tick += ref new EventHandler<Object^>(this,&MainPage::OnTick);
}
void MainPage::OnTick(Object^ sender, Object^ e) {
    // do something on each tick here ...
}

설명

DispatcherTimer를 사용하여 UI 스레드를 생성하는 동일한 스레드에서 코드를 실행할 수 있습니다. 이 스레드에서 실행되는 코드에는 UI 스레드에서만 만들고 수정할 수 있는 개체를 만들고 수정할 수 있는 권한이 있습니다. 코드가 UI 스레드에서 실행되도록 지정하려면 Interval 속성을 설정한 다음 Start 메서드를 호출합니다. Interval에 지정된 시간이 경과한 후에 Tick 이벤트가 발생합니다. Stop 메서드가 호출되거나 앱이 종료되거나 앱이 일시 중단될 때까지 동일한 간격으로 계속 실행됩니다(일시 중단 발생).

DispatcherTimer의 한 가지 시나리오는 센서 값의 변경 내용이 순전히 이벤트 기반이 아니거나 이벤트가 원하는 세분성을 제공하지 않는 센서의 속성을 검사 것입니다. 가속도계 샘플에서 볼 수 있습니다.

DispatcherTimer의 다른 시나리오에는 관련 이벤트가 없는 상태 변경 내용 확인 또는 스토리보드 애니메이션 또는 양방향 바인딩을 사용할 수 없는 정기적인 UI 업데이트가 포함됩니다.

Microsoft Silverlight 또는 WPF(Windows Presentation Foundation) 코드를 마이그레이션하는 경우 DispatcherTimer 및 관련 디스패처는 별도의 System.Windows.Threading 네임스페이스에 있었습니다. Windows 런타임 Windows.UI.Xaml.Threading 네임스페이스가 없으므로 이 클래스는 Windows.UI.Xaml에 있습니다.

처리기에서 UI 스레드로 아무 작업도 수행하지 않고 타이머만 필요한 경우 ThreadPoolTimer를 대신 사용할 수도 있습니다. 또한 ThreadPoolTimer 또는 .NET 작업과 같은 기술의 경우 UI 스레드에서 완전히 격리되지 않습니다. CoreDispatcher.RunAsync를 사용하여 UI 스레드에 비동기적으로 할당할 수 있습니다.

생성자

DispatcherTimer()

DispatcherTimer 클래스의 새 instance 초기화합니다.

속성

Interval

타이머 틱 사이의 시간을 가져오거나 설정합니다.

IsEnabled

타이머가 실행 중인지 여부를 나타내는 값을 가져옵니다.

메서드

Start()

DispatcherTimer를 시작합니다.

Stop()

DispatcherTimer를 중지합니다.

이벤트

Tick

타이머 간격이 경과되면 발생합니다.

적용 대상

추가 정보