다음을 통해 공유


스레드 타이머

업데이트: 2007년 11월

System.Threading.Timer 클래스는 작업을 별도의 스레드에서 정기적으로 실행하는 데 유용합니다. 예를 들어, 데이터베이스의 상태 및 무결성을 검사하거나 중요한 파일을 백업할 때 스레드 타이머를 사용할 수 있습니다.

스레드 타이머 예제

다음 예제에서는 2초마다 작업을 시작하고 플래그를 사용하여 타이머를 중지하는 Dispose 메서드를 시작합니다. 이 예제에서는 상태를 출력 창에 나타내므로 코드를 테스트하기 전에 Ctrl+Alt+O를 눌러 출력 창을 표시해야 합니다.

Class StateObjClass
    ' Used to hold parameters for calls to TimerTask
    Public SomeValue As Integer
    Public TimerReference As System.Threading.Timer
    Public TimerCanceled As Boolean
End Class

Sub RunTimer()
    Dim StateObj As New StateObjClass
    StateObj.TimerCanceled = False
    StateObj.SomeValue = 1
    Dim TimerDelegate As New Threading.TimerCallback(AddressOf TimerTask)
    ' Create a timer that calls a procedure every 2 seconds.
    ' Note: There is no Start method; the timer starts running as soon as 
    ' the instance is created.
    Dim TimerItem As New System.Threading.Timer(TimerDelegate, StateObj, _
                                                2000, 2000)
    StateObj.TimerReference = TimerItem  ' Save a reference for Dispose.

    While StateObj.SomeValue < 10 ' Run for ten loops.
        System.Threading.Thread.Sleep(1000)  ' Wait one second.
    End While

    StateObj.TimerCanceled = True  ' Request Dispose of the timer object.
End Sub

Sub TimerTask(ByVal StateObj As Object)
    Dim State As StateObjClass = CType(StateObj, StateObjClass)
    ' Use the interlocked class to increment the counter variable.
    System.Threading.Interlocked.Increment(State.SomeValue)
    System.Diagnostics.Debug.WriteLine("Launched new thread  " & Now)
    If State.TimerCanceled Then    ' Dispose Requested.
        State.TimerReference.Dispose()
        System.Diagnostics.Debug.WriteLine("Done  " & Now)
    End If
End Sub

스레드 타이머는 콘솔 응용 프로그램을 개발할 때와 같이 System.Windows.Forms.Timer 개체를 사용할 수 없는 경우에 특히 유용합니다.

참고 항목

개념

Visual Basic의 고급 다중 스레딩

다중 스레드 응용 프로그램

참조

System.Threading

SyncLock 문