Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase Timer

 

Publicado: octubre de 2016

Proporciona un mecanismo para ejecutar un método en un subproceso del grupo de subprocesos en intervalos especificados. Esta clase no puede heredarse.

Para examinar el código fuente de .NET Framework de este tipo, consulte el origen de referencia.

Espacio de nombres:   System.Threading
Ensamblado:  mscorlib (en mscorlib.dll)

System.Object
  System.MarshalByRefObject
    System.Threading.Timer

<ComVisibleAttribute(True)>
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,
	ExternalThreading := True)>
Public NotInheritable Class Timer
	Inherits MarshalByRefObject
	Implements IDisposable

NombreDescripción
System_CAPS_pubmethodTimer(TimerCallback)

Inicializa una nueva instancia de la Timer clase con un período y un límite infinitos de tiempo, con el recién creado Timer objeto como objeto de estado.

System_CAPS_pubmethodTimer(TimerCallback, Object, Int32, Int32)

Inicializa una nueva instancia de la Timer clase, utilizando un entero de 32 bits con signo para especificar el intervalo de tiempo.

System_CAPS_pubmethodTimer(TimerCallback, Object, Int64, Int64)

Inicializa una nueva instancia de la Timer clase, utilizando enteros de 64 bits con signo para medir los intervalos de tiempo.

System_CAPS_pubmethodTimer(TimerCallback, Object, TimeSpan, TimeSpan)

Inicializa una nueva instancia de la Timer clase mediante TimeSpan valores para medir los intervalos de tiempo.

System_CAPS_pubmethodTimer(TimerCallback, Object, UInt32, UInt32)

Inicializa una nueva instancia de la Timer clase, utilizando enteros de 32 bits sin signo para medir los intervalos de tiempo.

NombreDescripción
System_CAPS_pubmethodChange(Int32, Int32)

Cambia el tiempo de inicio y el intervalo entre las distintas invocaciones de método para un temporizador, utilizando enteros de 32 bits con signo para medir los intervalos de tiempo.

System_CAPS_pubmethodChange(Int64, Int64)

Cambia el tiempo de inicio y el intervalo entre las distintas invocaciones de método para un temporizador, utilizando enteros de 64 bits con signo para medir los intervalos de tiempo.

System_CAPS_pubmethodChange(TimeSpan, TimeSpan)

Cambia la hora de inicio y el intervalo entre las distintas invocaciones de método para un temporizador, utilizando TimeSpan valores para medir los intervalos de tiempo.

System_CAPS_pubmethodChange(UInt32, UInt32)

Cambia el tiempo de inicio y el intervalo entre las distintas invocaciones de método para un temporizador, utilizando enteros de 32 bits sin signo para medir los intervalos de tiempo.

System_CAPS_pubmethodCreateObjRef(Type)

Crea un objeto que contiene toda la información pertinente necesaria para generar a un proxy utilizado para comunicarse con un objeto remoto.(Heredado de MarshalByRefObject).

System_CAPS_pubmethodDispose()

Libera todos los recursos utilizados por la instancia actual de Timer.

System_CAPS_pubmethodDispose(WaitHandle)

Libera todos los recursos utilizados por la instancia actual de Timer e indica el momento se ha eliminado el temporizador.

System_CAPS_pubmethodEquals(Object)

Determina si el objeto especificado es igual al objeto actual.(Heredado de Object).

System_CAPS_pubmethodGetHashCode()

Sirve como la función hash predeterminada.(Heredado de Object).

System_CAPS_pubmethodGetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.(Heredado de MarshalByRefObject).

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_pubmethodInitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.(Heredado de MarshalByRefObject).

System_CAPS_pubmethodToString()

Devuelve una cadena que representa al objeto actual. (Heredado de Object).

System_CAPS_noteNota

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#mscorlib/system/threading/timer.cs#051a39d380760b26. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

Use a T:System.Threading.TimerCallback delegate to specify the method you want the T:System.Threading.Timer to execute. The signature of the T:System.Threading.TimerCallback delegate is:

Sub TimerCallback(state As Object)

The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a T:System.Threading.ThreadPool thread supplied by the system.

System_CAPS_tipSugerencia

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Windows.Forms.Timer, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.

  • System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

When you create a timer, you can specify an amount of time to wait before the first execution of the method (due time), and an amount of time to wait between subsequent executions (period). The T:System.Threading.Timer class has the same resolution as the system clock. This means that if the period is less than the resolution of the system clock, the T:System.Threading.TimerCallback delegate will execute at intervals defined by the resolution of the system clock, which is approximately 15 milliseconds on Windows 7 and Windows 8 systems. You can change the due time and period, or disable the timer, by using the M:System.Threading.Timer.Change(System.Int32,System.Int32) method.

System_CAPS_noteNota

As long as you are using a T:System.Threading.Timer, you must keep a reference to it. As with any managed object, a T:System.Threading.Timer is subject to garbage collection when there are no references to it. The fact that a T:System.Threading.Timer is still active does not prevent it from being collected.

When a timer is no longer needed, use the Overload:System.Threading.Timer.Dispose method to free the resources held by the timer. Note that callbacks can occur after the M:System.Threading.Timer.Dispose method overload has been called, because the timer queues callbacks for execution by thread pool threads. You can use the M:System.Threading.Timer.Dispose(System.Threading.WaitHandle) method overload to wait until all callbacks have completed.

The callback method executed by the timer should be reentrant, because it is called on T:System.Threading.ThreadPool threads. The callback can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the callback, or if all thread pool threads are in use and the callback is queued multiple times.

System_CAPS_noteNota

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.

The following example defines a StatusChecker class that includes a CheckStatus method whose signature is the same as the T:System.Threading.TimerCallback delegate. The state argument of the CheckStatus method is an T:System.Threading.AutoResetEvent object that is used to synchronize the application thread and the thread pool thread that executes the callback delegate. The StatusChecker class also includes two state variables:

invokeCount

Indicates the number of times the callback method has been invoked.

maxCount

Determines the maximum number of times the callback method should be invoked.

The application thread creates the timer, which waits one second and then executes the CheckStatus callback method every 250 milliseconds. The application thread then blocks until the T:System.Threading.AutoResetEvent object is signaled. When the CheckStatus callback method executes maxCount times, it calls the AutoResetEvent.Set method to set the state of the T:System.Threading.AutoResetEvent object to signaled. The first time this happens, the application thread calls the M:System.Threading.Timer.Change(System.Int32,System.Int32) method so that the callback method now executes every half second. It once again blocks until the T:System.Threading.AutoResetEvent object is signaled. When this happens, the timer is destroyed by calling its M:System.Threading.Timer.Dispose method, and the application terminates.

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.

Plataforma universal de Windows
Disponible desde 8.1
.NET Framework
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

This type is thread safe.

Volver al principio
Mostrar: