Timer Timer Timer Timer Class

Definición

Implementa un temporizador que genera un evento en los intervalos definidos por el usuario.Implements a timer that raises an event at user-defined intervals. Este temporizador está optimizado para su uso en aplicaciones de Windows Forms y se debe utilizar en una ventana.This timer is optimized for use in Windows Forms applications and must be used in a window.

public ref class Timer : System::ComponentModel::Component
public class Timer : System.ComponentModel.Component
type Timer = class
    inherit Component
Public Class Timer
Inherits Component
Herencia

Ejemplos

El ejemplo siguiente implementa un temporizador de intervalo simple, que dispara una alarma cada cinco segundos.The following example implements a simple interval timer, which sets off an alarm every five seconds. Cuando se produce la alarma, un MessageBox muestra un recuento del número de veces que la alarma se ha iniciado y pregunta al usuario si el temporizador debe continuar ejecutándose.When the alarm occurs, a MessageBox displays a count of the number of times the alarm has started and prompts the user as to whether the timer should continue to run.

public ref class Class1
{
private:
   static System::Windows::Forms::Timer^ myTimer = gcnew System::Windows::Forms::Timer;
   static int alarmCounter = 1;
   static bool exitFlag = false;

   // This is the method to run when the timer is raised.
   static void TimerEventProcessor( Object^ /*myObject*/, EventArgs^ /*myEventArgs*/ )
   {
      myTimer->Stop();
      
      // Displays a message box asking whether to continue running the timer.
      if ( MessageBox::Show( "Continue running?", String::Format( "Count is: {0}", alarmCounter ), MessageBoxButtons::YesNo ) == DialogResult::Yes )
      {
         
         // Restarts the timer and increments the counter.
         alarmCounter += 1;
         myTimer->Enabled = true;
      }
      else
      {
         
         // Stops the timer.
         exitFlag = true;
      }
   }


public:
   static void Main()
   {
      
      /* Adds the event and the event handler for the method that will 
                process the timer event to the timer. */
      myTimer->Tick += gcnew EventHandler( TimerEventProcessor );
      
      // Sets the timer interval to 5 seconds.
      myTimer->Interval = 5000;
      myTimer->Start();
      
      // Runs the timer, and raises the event.
      while ( exitFlag == false )
      {
         
         // Processes all the events in the queue.
         Application::DoEvents();
      }
   }

};

int main()
{
   Class1::Main();
}

public class Class1 {
    static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    static int alarmCounter = 1;
    static bool exitFlag = false;
 
    // This is the method to run when the timer is raised.
    private static void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs) {
       myTimer.Stop();
 
       // Displays a message box asking whether to continue running the timer.
       if(MessageBox.Show("Continue running?", "Count is: " + alarmCounter, 
          MessageBoxButtons.YesNo) == DialogResult.Yes) {
          // Restarts the timer and increments the counter.
          alarmCounter +=1;
          myTimer.Enabled = true;
       }
       else {
          // Stops the timer.
          exitFlag = true;
       }
    }
 
    public static int Main() {
       /* Adds the event and the event handler for the method that will 
          process the timer event to the timer. */
       myTimer.Tick += new EventHandler(TimerEventProcessor);
 
       // Sets the timer interval to 5 seconds.
       myTimer.Interval = 5000;
       myTimer.Start();
 
       // Runs the timer, and raises the event.
       while(exitFlag == false) {
          // Processes all the events in the queue.
          Application.DoEvents();
       }
    return 0;
    }
 }
    
Public Class Class1
    Private Shared WithEvents myTimer As New System.Windows.Forms.Timer()
    Private Shared alarmCounter As Integer = 1
    Private Shared exitFlag As Boolean = False    
    
    ' This is the method to run when the timer is raised.
    Private Shared Sub TimerEventProcessor(myObject As Object, _
                                           ByVal myEventArgs As EventArgs) _
                                       Handles myTimer.Tick
        myTimer.Stop()
        
        ' Displays a message box asking whether to continue running the timer.
        If MessageBox.Show("Continue running?", "Count is: " & alarmCounter, _
                            MessageBoxButtons.YesNo) = DialogResult.Yes Then
            ' Restarts the timer and increments the counter.
            alarmCounter += 1
            myTimer.Enabled = True
        Else
            ' Stops the timer.
            exitFlag = True
        End If
    End Sub
    
    Public Shared Sub Main()
        ' Adds the event and the event handler for the method that will
        ' process the timer event to the timer.
        
        ' Sets the timer interval to 5 seconds.
        myTimer.Interval = 5000
        myTimer.Start()
        
        ' Runs the timer, and raises the event.
        While exitFlag = False
            ' Processes all the events in the queue.
            Application.DoEvents()
        End While

    End Sub    

End Class

Comentarios

Un Timer se usa para generar un evento a intervalos definidos por el usuario.A Timer is used to raise an event at user-defined intervals. Este temporizador de Windows está diseñado para un entorno de un único subproceso donde se usan los subprocesos de interfaz de usuario para realizar el procesamiento.This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. Requiere que el código de usuario tiene un suministro de mensajes de interfaz de usuario y siempre funcionan desde el mismo subproceso o calcular las referencias de la llamada a otro subproceso.It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

Cuando se usa este temporizador, utilice el Tick eventos para realizar una operación de sondeo o para mostrar una pantalla de presentación para un período de tiempo especificado.When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Cada vez que el Enabled propiedad está establecida en true y el Interval propiedad es mayor que cero, el Tick evento se desencadena en los intervalos basados en el Interval configuración de la propiedad.Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.

Esta clase proporciona métodos para establecer el intervalo y para iniciar y detener el temporizador.This class provides methods to set the interval, and to start and stop the timer.

Nota

El componente Timer de formularios Windows Forms es de subproceso único y está limitado a una precisión de 55 milisegundos.The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. Si necesita un temporizador multiproceso con mayor precisión, use la Timer clase en el System.Timers espacio de nombres.If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

Constructores

Timer() Timer() Timer() Timer()

Inicializa una nueva instancia de la clase Timer.Initializes a new instance of the Timer class.

Timer(IContainer) Timer(IContainer) Timer(IContainer) Timer(IContainer)

Inicializa una nueva instancia de la clase Timer junto con el contenedor indicado.Initializes a new instance of the Timer class together with the specified container.

Propiedades

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

Obtiene un valor que indica si el componente puede generar un evento.Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container Container Container Container

Obtiene IContainer que contiene Component.Gets the IContainer that contains the Component.

(Inherited from Component)
DesignMode DesignMode DesignMode DesignMode

Obtiene un valor que indica si Component está actualmente en modo de diseño.Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Enabled Enabled Enabled Enabled

Obtiene o establece si el temporizador está funcionando.Gets or sets whether the timer is running.

Events Events Events Events

Obtiene la lista de controladores de eventos asociados a Component.Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Interval Interval Interval Interval

Obtiene o establece el tiempo, en milisegundos, que ha de transcurrir antes de provocarse el evento Tick en relación con la última aparición del evento Tick.Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.

Site Site Site Site

Obtiene o establece el ISite de Component.Gets or sets the ISite of the Component.

(Inherited from Component)
Tag Tag Tag Tag

Obtiene o establece una cadena arbitraria que representa algún tipo de estado del usuario.Gets or sets an arbitrary string representing some type of user state.

Métodos

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos que usa Component.Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Se deshace de los recursos (distintos de la memoria) utilizados por el temporizador.Disposes of the resources, other than memory, used by the timer.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

Devuelve un objeto que representa el servicio suministrado por Component o por Container.Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnTick(EventArgs) OnTick(EventArgs) OnTick(EventArgs) OnTick(EventArgs)

Genera el evento Tick.Raises the Tick event.

Start() Start() Start() Start()

Inicia el temporizador.Starts the timer.

Stop() Stop() Stop() Stop()

Detiene el temporizador.Stops the timer.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa Timer.Returns a string that represents the Timer.

Eventos

Disposed Disposed Disposed Disposed

Se produce cuando el componente se elimina mediante una llamada al método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
Tick Tick Tick Tick

Se produce cuando ha transcurrido el intervalo del temporizador especificado y está habilitado el temporizador.Occurs when the specified timer interval has elapsed and the timer is enabled.

Se aplica a