Timer 클래스

정의

지정된 간격으로 스레드 풀 스레드에 대해 메서드를 실행하는 메커니즘을 제공합니다. 이 클래스는 상속될 수 없습니다.

public ref class Timer sealed : IDisposable
public ref class Timer sealed : MarshalByRefObject, IAsyncDisposable, IDisposable
public ref class Timer sealed : MarshalByRefObject, System::Threading::ITimer
public ref class Timer sealed : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : IDisposable
public sealed class Timer : MarshalByRefObject, IAsyncDisposable, IDisposable
public sealed class Timer : MarshalByRefObject, System.Threading.ITimer
public sealed class Timer : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface IDisposable
    interface ITimer
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
Public NotInheritable Class Timer
Implements IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IAsyncDisposable, IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements ITimer
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IDisposable
상속
Timer
상속
특성
구현

예제

다음 예제에서는 시그니처가 StatusChecker 대리자와 동일한 메서드를 포함하는 CheckStatus 클래스를 TimerCallback 정의합니다. state 메서드의 CheckStatus 인수는 AutoResetEvent 애플리케이션 스레드와 콜백 대리자를 실행하는 스레드 풀 스레드를 동기화하는 데 사용되는 개체입니다. 클래스에는 StatusChecker 다음 두 가지 상태 변수도 포함됩니다.

invokeCount 콜백 메서드가 호출된 횟수를 나타냅니다.

maxCount 콜백 메서드를 호출해야 하는 최대 횟수를 결정합니다.

애플리케이션 스레드는 1초 동안 기다린 다음 250밀리초마다 콜백 메서드를 실행하는 CheckStatus 타이머를 만듭니다. 될 때까지 애플리케이션 스레드를 차단 합니다 AutoResetEvent 개체의 신호를 받습니다. 콜백 메서드가 CheckStatus 횟수 실행 maxCount 될 때 메서드를 AutoResetEvent.Set 호출하여 개체의 AutoResetEvent 상태를 신호로 설정합니다. 처음 이런 애플리케이션 스레드 호출을 Change(Int32, Int32) 메서드 콜백 메서드는 이제 0.5 초 마다 실행 되도록 합니다. 개체가 AutoResetEvent 신호를 보낼 때까지 다시 한 번 차단됩니다. 이 경우 타이머를 호출 하 여 소멸 됩니다 해당 Dispose 메서드 및 애플리케이션을 종료 합니다.

using namespace System;
using namespace System::Threading;

ref class StatusChecker
{
private:
    int invokeCount, maxCount;

public:
    StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    void CheckStatus(Object^ stateInfo)
    {
        AutoResetEvent^ autoEvent = dynamic_cast<AutoResetEvent^>(stateInfo);
        Console::WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.",
                           DateTime::Now, ++invokeCount);

        if (invokeCount == maxCount) {
            // Reset the counter and signal the waiting thread.
            invokeCount  = 0;
            autoEvent->Set();
        }
    }
};

ref class TimerExample
{
public:
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        AutoResetEvent^ autoEvent = gcnew AutoResetEvent(false);

        StatusChecker^ statusChecker = gcnew StatusChecker(10);

        // Create a delegate that invokes methods for the timer.
        TimerCallback^ tcb =
           gcnew TimerCallback(statusChecker, &StatusChecker::CheckStatus);

        // Create a timer that invokes CheckStatus after one second, 
        // and every 1/4 second thereafter.
        Console::WriteLine("{0:h:mm:ss.fff} Creating timer.\n",
                           DateTime::Now);
        Timer^ stateTimer = gcnew Timer(tcb, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent->WaitOne(5000, false);
        stateTimer->Change(0, 500);
        Console::WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent->WaitOne(5000, false);
        stateTimer->~Timer();
        Console::WriteLine("\nDestroying timer.");
    }
};

int main()
{
    TimerExample::Main();
}
// The example displays output like the following:
//       11:59:54.202 Creating timer.
//       
//       11:59:55.217 Checking status  1.
//       11:59:55.466 Checking status  2.
//       11:59:55.716 Checking status  3.
//       11:59:55.968 Checking status  4.
//       11:59:56.218 Checking status  5.
//       11:59:56.470 Checking status  6.
//       11:59:56.722 Checking status  7.
//       11:59:56.972 Checking status  8.
//       11:59:57.223 Checking status  9.
//       11:59:57.473 Checking status 10.
//       
//       Changing period to .5 seconds.
//       
//       11:59:57.474 Checking status  1.
//       11:59:57.976 Checking status  2.
//       11:59:58.476 Checking status  3.
//       11:59:58.977 Checking status  4.
//       11:59:59.477 Checking status  5.
//       11:59:59.977 Checking status  6.
//       12:00:00.478 Checking status  7.
//       12:00:00.980 Checking status  8.
//       12:00:01.481 Checking status  9.
//       12:00:01.981 Checking status 10.
//       
//       Destroying timer.
using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        var autoEvent = new AutoResetEvent(false);
        
        var statusChecker = new StatusChecker(10);

        // Create a timer that invokes CheckStatus after one second, 
        // and every 1/4 second thereafter.
        Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", 
                          DateTime.Now);
        var stateTimer = new Timer(statusChecker.CheckStatus, 
                                   autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne();
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne();
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    private int invokeCount;
    private int  maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal the waiting thread.
            invokeCount = 0;
            autoEvent.Set();
        }
    }
}
// The example displays output like the following:
//       11:59:54.202 Creating timer.
//       
//       11:59:55.217 Checking status  1.
//       11:59:55.466 Checking status  2.
//       11:59:55.716 Checking status  3.
//       11:59:55.968 Checking status  4.
//       11:59:56.218 Checking status  5.
//       11:59:56.470 Checking status  6.
//       11:59:56.722 Checking status  7.
//       11:59:56.972 Checking status  8.
//       11:59:57.223 Checking status  9.
//       11:59:57.473 Checking status 10.
//       
//       Changing period to .5 seconds.
//       
//       11:59:57.474 Checking status  1.
//       11:59:57.976 Checking status  2.
//       11:59:58.476 Checking status  3.
//       11:59:58.977 Checking status  4.
//       11:59:59.477 Checking status  5.
//       11:59:59.977 Checking status  6.
//       12:00:00.478 Checking status  7.
//       12:00:00.980 Checking status  8.
//       12:00:01.481 Checking status  9.
//       12:00:01.981 Checking status 10.
//       
//       Destroying timer.
Imports System.Threading

Public Module Example
    Public Sub Main()
        ' Use an AutoResetEvent to signal the timeout threshold in the
        ' timer callback has been reached.
        Dim autoEvent As New AutoResetEvent(False)

        Dim statusChecker As New StatusChecker(10)

        ' Create a timer that invokes CheckStatus after one second, 
        ' and every 1/4 second thereafter.
        Console.WriteLine("{0:h:mm:ss.fff} Creating timer." & vbCrLf, 
                          DateTime.Now)
        Dim stateTimer As New Timer(AddressOf statusChecker.CheckStatus, 
                                    autoEvent, 1000, 250)

        ' When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne()
        stateTimer.Change(0, 500)
        Console.WriteLine(vbCrLf & "Changing period to .5 seconds." & vbCrLf)

        ' When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne()
        stateTimer.Dispose()
        Console.WriteLine(vbCrLf & "Destroying timer.")
    End Sub
End Module

Public Class StatusChecker
    Dim invokeCount, maxCount As Integer 

    Sub New(count As Integer)
        invokeCount  = 0
        maxCount = count
    End Sub

    ' The timer callback method.
    Sub CheckStatus(stateInfo As Object)
        Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
        invokeCount += 1
        Console.WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.", 
                          DateTime.Now, invokeCount)
        If invokeCount = maxCount Then
            ' Reset the counter and signal the waiting thread.
            invokeCount = 0
            autoEvent.Set()
        End If
    End Sub
End Class
' The example displays output like the following:
'       11:59:54.202 Creating timer.
'       
'       11:59:55.217 Checking status  1.
'       11:59:55.466 Checking status  2.
'       11:59:55.716 Checking status  3.
'       11:59:55.968 Checking status  4.
'       11:59:56.218 Checking status  5.
'       11:59:56.470 Checking status  6.
'       11:59:56.722 Checking status  7.
'       11:59:56.972 Checking status  8.
'       11:59:57.223 Checking status  9.
'       11:59:57.473 Checking status 10.
'       
'       Changing period to .5 seconds.
'       
'       11:59:57.474 Checking status  1.
'       11:59:57.976 Checking status  2.
'       11:59:58.476 Checking status  3.
'       11:59:58.977 Checking status  4.
'       11:59:59.477 Checking status  5.
'       11:59:59.977 Checking status  6.
'       12:00:00.478 Checking status  7.
'       12:00:00.980 Checking status  8.
'       12:00:01.481 Checking status  9.
'       12:00:01.981 Checking status 10.
'       
'       Destroying timer.

설명

대리자를 TimerCallback 사용하여 를 실행할 메서드를 Timer 지정합니다. 대리자의 TimerCallback 서명은 다음과 같습니다.

void TimerCallback(Object state)
void TimerCallback(Object state)
Sub TimerCallback(state As Object)

타이머 대리자는 타이머가 생성될 때 지정되며 변경할 수 없습니다. 메서드는 타이머를 만든 스레드에서 실행되지 않습니다. 시스템에서 제공하는 스레드에서 ThreadPool 실행됩니다.

.NET에는 다양한 기능을 제공하는 여러 타이머 클래스가 포함되어 있습니다.

  • System.Timers.Timer이벤트를 실행하고 정기적으로 하나 이상의 이벤트 싱크에서 코드를 실행합니다. 클래스는 다중 스레드 환경에서 서버 기반 또는 서비스 구성 요소로 사용하기 위한 것입니다. 사용자 인터페이스가 없으며 런타임에 표시되지 않습니다.
  • System.Threading.Timer- 스레드 풀 스레드에서 정기적으로 단일 콜백 메서드를 실행합니다. 콜백 메서드는 타이머가 인스턴스화되어 변경할 수 없을 때 정의됩니다. 클래스와 System.Timers.Timer 마찬가지로 이 클래스는 다중 스레드 환경에서 서버 기반 또는 서비스 구성 요소로 사용하기 위한 것입니다. 사용자 인터페이스가 없고 런타임에 표시되지 않습니다.
  • System.Windows.Forms.Timer은 이벤트를 발생시키고 정기적으로 하나 이상의 이벤트 싱크에서 코드를 실행하는 Windows Forms 구성 요소입니다. 구성 요소에는 사용자 인터페이스가 없으며 단일 스레드 환경에서 사용하도록 설계되었습니다. UI 스레드에서 실행됩니다.
  • System.Web.UI.Timer(.NET Framework만 해당) 비동기 또는 동기 웹 페이지 포스트백을 정기적으로 수행하는 ASP.NET 구성 요소입니다.
  • System.Windows.Threading.DispatcherTimer- 큐에 Dispatcher 통합된 타이머입니다. 이 타이머는 지정된 시간 간격으로 지정된 우선 순위로 처리됩니다.

타이머를 만들 때 메서드의 첫 번째 실행 전에 대기할 시간(기한) 및 후속 실행(기간) 사이에 대기할 시간을 지정할 수 있습니다. 클래스의 Timer 해상도는 시스템 클록과 동일합니다. 즉, TimerCallback 마침표가 시스템 클록의 해상도보다 작으면 대리자는 Windows 7 및 Windows 8 시스템에서 약 15밀리초인 시스템 클록의 해상도로 정의된 간격으로 실행됩니다. 메서드를 사용하여 Change 기한 및 기간을 변경하거나 타이머를 사용하지 않도록 설정할 수 있습니다.

참고

를 사용하는 Timer한 에 대한 참조를 유지해야 합니다. 관리되는 개체와 마찬가지로 에 Timer 대한 참조가 없는 경우 가비지 수집이 적용됩니다. 가 Timer 여전히 활성 상태라는 사실 때문에 수집되는 것을 막을 수 없습니다.

참고

사용되는 시스템 클록은 GetTickCount에서 사용하는 것과 동일한 클록으로, timeBeginPeriodtimeEndPeriod로 변경된 내용의 영향을 받지 않습니다.

타이머가 더 이상 필요하지 않은 경우 메서드를 Dispose 사용하여 타이머가 보유한 리소스를 해제합니다. 타이머는 스레드 풀 스레드에서 실행하기 위해 콜백을 큐에 넣기 때문에 메서드 오버로드가 호출된 후에 Dispose() 콜백이 발생할 수 있습니다. 메서드 오버로드를 Dispose(WaitHandle) 사용하여 모든 콜백이 완료될 때까지 기다릴 수 있습니다.

타이머가 실행하는 콜백 메서드는 스레드에서 ThreadPool 호출되므로 다시 활성화되어야 합니다. 타이머 간격이 콜백을 실행하는 데 필요한 시간보다 작거나 모든 스레드 풀 스레드가 사용 중이고 콜백이 여러 번 큐에 대기 중인 경우 두 스레드 풀 스레드에서 콜백을 동시에 실행할 수 있습니다.

참고

System.Threading.Timer 는 콜백 메서드를 사용하고 스레드 풀 스레드에서 제공하는 간단하고 간단한 타이머입니다. 사용자 인터페이스 스레드에서 콜백이 발생하지 않으므로 Windows Forms 사용하지 않는 것이 좋습니다. System.Windows.Forms.Timer는 Windows Forms 사용하기에 더 적합합니다. 서버 기반 타이머 기능의 경우 이벤트를 발생시키고 추가 기능이 있는 를 사용하는 System.Timers.Timer것이 좋습니다.

생성자

Timer(TimerCallback)

새로 만든 Timer 개체를 상태 개체로 사용하고 무한 기간 및 무한 만료 예정 시간을 지정하여 Timer 클래스의 새 인스턴스를 초기화합니다.

Timer(TimerCallback, Object, Int32, Int32)

부호 있는 32비트 정수로 시간 간격을 지정하여 Timer 클래스의 새 인스턴스를 초기화합니다.

Timer(TimerCallback, Object, Int64, Int64)

부호 있는 64비트 정수로 시간 간격을 측정하여 Timer 클래스의 새 인스턴스를 초기화합니다.

Timer(TimerCallback, Object, TimeSpan, TimeSpan)

TimeSpan 값을 사용하여 시간 간격을 측정하여 Timer 클래스의 새 인스턴스를 초기화합니다.

Timer(TimerCallback, Object, UInt32, UInt32)

부호 있는 32비트 정수로 시간 간격을 측정하여 Timer 클래스의 새 인스턴스를 초기화합니다.

속성

ActiveCount

현재 활성 상태인 타이머의 수를 가져옵니다. 활성 타이머는 미래의 특정 시점에 작동하도록 등록되어 있으며 아직 취소되지 않았습니다.

메서드

Change(Int32, Int32)

부호 있는 32비트 정수로 시간 간격을 측정하여 타이머 시작 시간 및 메서드 호출 사이의 간격을 변경합니다.

Change(Int64, Int64)

부호 있는 64비트 정수로 시간 간격을 측정하여 타이머 시작 시간 및 메서드 호출 사이의 간격을 변경합니다.

Change(TimeSpan, TimeSpan)

TimeSpan 값으로 시간 간격을 측정하여 타이머 시작 시간 및 메서드 호출 사이의 간격을 변경합니다.

Change(UInt32, UInt32)

부호 없는 32비트 정수로 시간 간격을 측정하여 타이머 시작 시간 및 메서드 호출 사이의 간격을 변경합니다.

CreateObjRef(Type)

원격 개체와 통신하는 데 사용되는 프록시 생성에 필요한 모든 관련 정보가 들어 있는 개체를 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
Dispose()

Timer의 현재 인스턴스에서 사용하는 모든 리소스를 해제합니다.

Dispose(WaitHandle)

Timer의 현재 인스턴스에서 사용하는 모든 리소스를 해제하고 타이머가 삭제되면 신호를 보냅니다.

DisposeAsync()

Timer의 현재 인스턴스에서 사용하는 모든 리소스를 해제합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
Finalize()

가비지 컬렉션이 회수하기 전에 개체가 리소스를 해제하고 다른 정리 작업을 수행할 수 있게 합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 현재의 수명 서비스 개체를 검색합니다.

(다음에서 상속됨 MarshalByRefObject)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
InitializeLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.

(다음에서 상속됨 MarshalByRefObject)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
MemberwiseClone(Boolean)

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

확장 메서드

ConfigureAwait(IAsyncDisposable, Boolean)

비동기 일회용에서 반환되는 작업을 대기하는 방법을 구성합니다.

적용 대상

스레드 보안

이 형식은 스레드로부터 안전합니다.

추가 정보