Timer Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Implementa un timer che genera un evento a intervalli definiti dall'utente. Questo timer è ottimizzato per l'uso nelle applicazioni Windows Form e deve essere usato in una finestra.
public ref class Timer : System::ComponentModel::Component
public class Timer : System.ComponentModel.Component
type Timer = class
inherit Component
Public Class Timer
Inherits Component
- Ereditarietà
Esempio
L'esempio seguente implementa un timer di intervallo semplice, che imposta un allarme ogni cinque secondi. Quando si verifica l'allarme, viene MessageBox visualizzato un conteggio del numero di volte in cui l'allarme è stato avviato e viene richiesto all'utente di specificare se il timer deve continuare a essere eseguito.
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 )
{
// 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) {
// 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
Commenti
Un Timer oggetto viene utilizzato per generare un evento a intervalli definiti dall'utente. Questo timer di Windows è progettato per un ambiente a thread singolo in cui i thread dell'interfaccia utente vengono usati per eseguire l'elaborazione. Richiede che il codice utente disponga di un pump di messaggi dell'interfaccia utente disponibile e che funzioni sempre dallo stesso thread o effettuare il marshalling della chiamata in un altro thread.
Quando si usa questo timer, usare l'evento Tick per eseguire un'operazione di polling o per visualizzare una schermata iniziale per un periodo di tempo specificato. Ogni volta che la Enabled proprietà è impostata su true e la Interval proprietà è maggiore di zero, l'evento Tick viene generato a intervalli in base all'impostazione della Interval proprietà.
Questa classe fornisce metodi per impostare l'intervallo e per avviare e arrestare il timer.
Annotazioni
Il componente Timer di Windows Form è a thread singolo ed è limitato a un'accuratezza di 55 millisecondi. Se è necessario un timer multithreading con maggiore accuratezza, usare la Timer classe nello spazio dei System.Timers nomi .
Costruttori
| Nome | Descrizione |
|---|---|
| Timer() |
Inizializza una nuova istanza della classe Timer. |
| Timer(IContainer) |
Inizializza una nuova istanza della Timer classe insieme al contenitore specificato. |
Proprietà
| Nome | Descrizione |
|---|---|
| CanRaiseEvents |
Ottiene un valore che indica se il componente può generare un evento. (Ereditato da Component) |
| Container |
Ottiene l'oggetto IContainer contenente l'oggetto Component. (Ereditato da Component) |
| DesignMode |
Ottiene un valore che indica se è Component attualmente in modalità progettazione. (Ereditato da Component) |
| Enabled |
Ottiene o imposta un valore che indica se il timer è in esecuzione. |
| Events |
Ottiene l'elenco dei gestori eventi associati a questo Componentoggetto . (Ereditato da Component) |
| Interval |
Ottiene o imposta l'ora, espressa in millisecondi, prima che l'evento Tick venga generato rispetto all'ultima occorrenza dell'evento Tick . |
| Site |
Ottiene o imposta l'oggetto ISite dell'oggetto Component. (Ereditato da Component) |
| Tag |
Ottiene o imposta una stringa arbitraria che rappresenta un tipo di stato utente. |
Metodi
| Nome | Descrizione |
|---|---|
| CreateObjRef(Type) |
Crea un oggetto che contiene tutte le informazioni pertinenti necessarie per generare un proxy utilizzato per comunicare con un oggetto remoto. (Ereditato da MarshalByRefObject) |
| Dispose() |
Rilascia tutte le risorse usate da Component. (Ereditato da Component) |
| Dispose(Boolean) |
Elimina le risorse, diverse dalla memoria, usate dal timer. |
| Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object) |
| GetHashCode() |
Funge da funzione hash predefinita. (Ereditato da Object) |
| GetLifetimeService() |
Obsoleti.
Recupera l'oggetto servizio di durata corrente che controlla i criteri di durata per questa istanza. (Ereditato da MarshalByRefObject) |
| GetService(Type) |
Restituisce un oggetto che rappresenta un servizio fornito da Component o da Container. (Ereditato da Component) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| InitializeLifetimeService() |
Obsoleti.
Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza. (Ereditato da MarshalByRefObject) |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| MemberwiseClone(Boolean) |
Crea una copia superficiale dell'oggetto corrente MarshalByRefObject . (Ereditato da MarshalByRefObject) |
| OnTick(EventArgs) |
Genera l'evento Tick. |
| Start() |
Avvia il timer. |
| Stop() |
Arresta il timer. |
| ToString() |
Restituisce una stringa che rappresenta l'oggetto Timer. |
Eventi
| Nome | Descrizione |
|---|---|
| Disposed |
Si verifica quando il componente viene eliminato da una chiamata al Dispose() metodo . (Ereditato da Component) |
| Tick |
Si verifica quando è trascorso l'intervallo timer specificato e il timer è abilitato. |