Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

Timer-Klasse

 

Veröffentlicht: Oktober 2016

Generiert ein Ereignis nach einem festgelegten Intervall, mit der Option zum Generieren wiederkehrender Ereignisse.

Informationen zum Durchsuchen des .NET Framework-Quellcodes für diesen Typ finden Sie in der Verweisquelle.

Namespace:   System.Timers
Assembly:  System (in System.dll)


[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class Timer : Component, ISupportInitialize

NameBeschreibung
System_CAPS_pubmethodTimer()

Initialisiert eine neue Instanz der Timer-Klasse und legt alle Eigenschaften auf die Anfangswerte fest.

System_CAPS_pubmethodTimer(Double)

Initialisiert eine neue Instanz der Timer-Klasse, dabei wird die Interval-Eigenschaft auf den angegebenen Wert in Millisekunden festgelegt.

NameBeschreibung
System_CAPS_pubpropertyAutoReset

Ruft einen booleschen Wert ab, der angibt, ob der Timer das Elapsed-Ereignis nur einmal (false) oder wiederholt (true) auslösen soll, oder legt diesen fest.

System_CAPS_protpropertyCanRaiseEvents

Ruft einen Wert ab, der angibt, ob die Komponente ein Ereignis auslösen kann. (Geerbt von „Component“.)

System_CAPS_pubpropertyContainer

Ruft den IContainer ab, der Component enthält. (Geerbt von „Component“.)

System_CAPS_protpropertyDesignMode

Ruft einen Wert, der angibt, ob die Component befindet sich derzeit im Entwurfsmodus befindet.(Geerbt von „Component“.)

System_CAPS_pubpropertyEnabled

Ruft einen Wert ab, der angibt, ob der Timer das Elapsed-Ereignis auslösen soll, oder legt diesen fest.

System_CAPS_protpropertyEvents

Ruft die Liste der Ereignishandler, die mit dieser verknüpft sind Component.(Geerbt von „Component“.)

System_CAPS_pubpropertyInterval

Ruft das Intervall in Millisekunden ab, in dem das Elapsed-Ereignis ausgelöst wird, oder legt dieses fest.

System_CAPS_pubpropertySite

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Ruft die Site ab, die die Timer-Klasse im Entwurfsmodus an ihren Container bindet, oder legt diese fest.(Überschreibt Component.Site.)

System_CAPS_pubpropertySynchronizingObject

Ruft das Objekt ab, das zum Marshallen von Ereignishandleraufrufen verwendet wird, die nach Ablauf eines Intervalls ausgegeben werden, oder legt dieses fest.

NameBeschreibung
System_CAPS_pubmethodBeginInit()

Beginnt die Laufzeitinitialisierung eines Timer, der in einem Formular oder von einer anderen Komponente verwendet wird.

System_CAPS_pubmethodClose()

Gibt die von der Timer verwendeten Ressourcen frei.

System_CAPS_pubmethodCreateObjRef(Type)

Erstellt ein Objekt, das alle relevanten Informationen, die zum Generieren eines Proxys für die Kommunikation mit einem Remoteobjekt verwendet die enthält.(Geerbt von „MarshalByRefObject“.)

System_CAPS_pubmethodDispose()

Gibt alle vom Component verwendeten Ressourcen frei.(Geerbt von „Component“.)

System_CAPS_protmethodDispose(Boolean)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Gibt alle von der aktuellen Timer-Klasse verwendeten Ressourcen frei.(Überschreibt Component.Dispose(Boolean).)

System_CAPS_pubmethodEndInit()

Beendet die Laufzeitinitialisierung eines Timer, der in einem Formular oder von einer anderen Komponente verwendet wird.

System_CAPS_pubmethodEquals(Object)

Bestimmt, ob das angegebene Objekt mit dem aktuellen Objekt identisch ist.(Geerbt von „Object“.)

System_CAPS_protmethodFinalize()

Gibt nicht verwaltete Ressourcen frei und führt andere Bereinigungsvorgänge durch, bevor die Component durch die Garbage Collection wieder zugänglich gemacht wird.(Geerbt von „Component“.)

System_CAPS_pubmethodGetHashCode()

Fungiert als die Standardhashfunktion.(Geerbt von „Object“.)

System_CAPS_pubmethodGetLifetimeService()

Ruft das Dienstobjekt für aktuellen Lebensdauer, das steuert, die lebensdauerrichtlinie für diese Instanz ab.(Geerbt von „MarshalByRefObject“.)

System_CAPS_protmethodGetService(Type)

Gibt ein Objekt zurück, das einen von der Component oder von deren Container bereitgestellten Dienst darstellt.(Geerbt von „Component“.)

System_CAPS_pubmethodGetType()

Ruft den Type der aktuellen Instanz ab.(Geerbt von „Object“.)

System_CAPS_pubmethodInitializeLifetimeService()

Ruft ein Lebensdauerdienstobjekt zur Steuerung der Lebensdauerrichtlinie für diese Instanz ab.(Geerbt von „MarshalByRefObject“.)

System_CAPS_protmethodMemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.(Geerbt von „Object“.)

System_CAPS_protmethodMemberwiseClone(Boolean)

Erstellt eine flache Kopie des aktuellen MarshalByRefObject Objekt.(Geerbt von „MarshalByRefObject“.)

System_CAPS_pubmethodStart()

Beginnt mit dem Auslösen des Elapsed-Ereignisses durch Festlegen von Enabled auf true.

System_CAPS_pubmethodStop()

Unterbricht das Auslösen des Elapsed-Ereignisses durch Festlegen von Enabled auf false.

System_CAPS_pubmethodToString()

Gibt eine String mit dem Namen der Component, sofern vorhanden. Diese Methode darf nicht überschrieben werden.(Geerbt von „Component“.)

NameBeschreibung
System_CAPS_pubeventDisposed

Tritt auf, wenn die Komponente durch einen Aufruf der Dispose Methode freigegeben wird.
(Geerbt von „Component“.)

System_CAPS_pubeventElapsed

Tritt ein, wenn das Intervall abläuft.

System_CAPS_noteHinweis

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#System/services/timers/system/timers/Timer.cs#897683f27faba082. 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/.

The T:System.Timers.Timer component is a server-based timer that raises an E:System.Timers.Timer.Elapsed event in your application after the number of milliseconds in the P:System.Timers.Timer.Interval property has elapsed. You can configure the T:System.Timers.Timer object to raise the event just once or repeatedly using the P:System.Timers.Timer.AutoReset property. Typically, a T:System.Timers.Timer object is declared at the class level so that it stays in scope as long as it is needed. You can then handle its E:System.Timers.Timer.Elapsed event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a T:System.Timers.Timer object to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.

System_CAPS_importantWichtig

The T:System.Timers.Timer class is available in the .NET Framework only. It is not included in the .NET Standard Library and is not available on other platforms, such as .NET Core or the Universal Windows Platform. On these platforms, as well as for portability across all .NET platforms, you should use the T:System.Threading.Timer class instead.

This type implements the T:System.IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

The server-based T:System.Timers.Timer class is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised E:System.Timers.Timer.Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

The T:System.Timers.Timer component raises the E:System.Timers.Timer.Elapsed event, based on the value (in milliseconds) of the P:System.Timers.Timer.Interval property. You can handle this event to perform the processing you need. For example, suppose that you have an online sales application that continuously posts sales orders to a database. The service that compiles the instructions for shipping operates on a batch of orders rather than processing each order individually. You could use a T:System.Timers.Timer to start the batch processing every 30 minutes.

System_CAPS_importantWichtig

The System.Timers.Timer class has the same resolution as the system clock. This means that the E:System.Timers.Timer.Elapsed event will fire at an interval defined by the resolution of the system clock if the P:System.Timers.Timer.Interval property is less than the resolution of the system clock. For more information, see the P:System.Timers.Timer.Interval property.

When P:System.Timers.Timer.AutoReset is set to false, a T:System.Timers.Timer object raises the E:System.Timers.Timer.Elapsed event only once, after the first P:System.Timers.Timer.Interval has elapsed. To keep raising the E:System.Timers.Timer.Elapsed event regularly at the interval defined by the P:System.Timers.Timer.Interval, set P:System.Timers.Timer.AutoReset to true, which is the default value.

The T:System.Timers.Timer component catches and suppresses all exceptions thrown by event handlers for the E:System.Timers.Timer.Elapsed event. This behavior is subject to change in future releases of the .NET Framework. Note, however, that this is not true of event handlers that execute asynchronously and include the await operator (in C#) or the Await operator (in Visual Basic). Exceptions thrown in these event handlers are propagated back to the calling thread, as the following example illustrates. For more information on exceptions thrown in asynchronous methods, see Exception Handling (Task Parallel Library).

using System;
using System.Threading.Tasks;
using System.Timers;

class Example
{
   static void Main()
   {
      Timer timer = new Timer(1000);
      timer.Elapsed += async ( sender, e ) => await HandleTimer();
      timer.Start();
      Console.Write("Press any key to exit... ");
      Console.ReadKey();
   }

   private static Task HandleTimer()
   {
     Console.WriteLine("\nHandler not implemented..." );
     throw new NotImplementedException();
   }
}
// The example displays output like the following:
//   Press any key to exit...
//   Handler not implemented...
//   
//   Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
//      at Example.HandleTimer()
//      at Example.<<Main>b__0>d__2.MoveNext()
//   --- End of stack trace from previous location where exception was thrown ---
//      at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
//      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
//      at System.Threading.ThreadPoolWorkQueue.Dispatch()

If the P:System.Timers.Timer.SynchronizingObject property is null, the E:System.Timers.Timer.Elapsed event is raised on a T:System.Threading.ThreadPool thread. If processing of the E:System.Timers.Timer.Elapsed event lasts longer than P:System.Timers.Timer.Interval, the event might be raised again on another T:System.Threading.ThreadPool thread. In this situation, the event handler should be reentrant.

System_CAPS_noteHinweis

The event-handling method might run on one thread at the same time that another thread calls the M:System.Timers.Timer.Stop method or sets the P:System.Timers.Timer.Enabled property to false. This might result in the E:System.Timers.Timer.Elapsed event being raised after the timer is stopped. The example code for the M:System.Timers.Timer.Stop method shows one way to avoid this race condition.

Even if P:System.Timers.Timer.SynchronizingObject is not null, E:System.Timers.Timer.Elapsed events can occur after the Overload:System.Timers.Timer.Dispose or M:System.Timers.Timer.Stop method has been called or after the P:System.Timers.Timer.Enabled property has been set to false, because the signal to raise the E:System.Timers.Timer.Elapsed event is always queued for execution on a thread pool thread. One way to resolve this race condition is to set a flag that tells the event handler for the E:System.Timers.Timer.Elapsed event to ignore subsequent events.

If you use the T:System.Timers.Timer class with a user interface element, such as a form or control, without placing the timer on that user interface element, assign the form or control that contains the T:System.Timers.Timer to the P:System.Timers.Timer.SynchronizingObject property, so that the event is marshaled to the user interface thread.

For a list of default property values for an instance of T:System.Timers.Timer, see the M:System.Timers.Timer.#ctor constructor.

System_CAPS_tipTipp

Be aware that the .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer (this topic): fires an event 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: 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 at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

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

The following example instantiates a System.Timers.Timer object that fires its E:System.Timers.Timer.Elapsed event every two seconds (2,000 milliseconds), sets up an event handler for the event, and starts the timer. The event handler displays the value of the P:System.Timers.ElapsedEventArgs.SignalTime property each time it is raised.

using System;
using System.Timers;

public class Example
{
   private static System.Timers.Timer aTimer;

   public static void Main()
   {
      SetTimer();

      Console.WriteLine("\nPress the Enter key to exit the application...\n");
      Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
      Console.ReadLine();
      aTimer.Stop();
      aTimer.Dispose();

      Console.WriteLine("Terminating the application...");
   }

   private static void SetTimer()
   {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
    }
}
// The example displays output like the following:
//       Press the Enter key to exit the application...
//
//       The application started at 09:40:29.068
//       The Elapsed event was raised at 09:40:31.084
//       The Elapsed event was raised at 09:40:33.100
//       The Elapsed event was raised at 09:40:35.100
//       The Elapsed event was raised at 09:40:37.116
//       The Elapsed event was raised at 09:40:39.116
//       The Elapsed event was raised at 09:40:41.117
//       The Elapsed event was raised at 09:40:43.132
//       The Elapsed event was raised at 09:40:45.133
//       The Elapsed event was raised at 09:40:47.148
//
//       Terminating the application...

.NET Framework
Verfügbar seit 1.1

Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Zurück zum Anfang
Anzeigen: