Timer in C#

PHPz
Release: 2023-08-24 19:05:02
forward
1553 people have browsed it

Timer in C#

The namespace used to set timers is System.Timers. The Timer class generates an event after a set interval and optionally generates recurring events.

First, create a timer object with a 5-second interval −

timer = new System.Timers.Timer(5000);
Copy after login

Set the timer elapsed event. This event occurs when the interval elapses −

timer.Elapsed += OnTimedEvent;
Copy after login

Start timing now. The Chinese translation of

timer.Enabled = true;
Copy after login

Example

is:

Example

using System;
using System.Timers;

public class Demo {
   private static Timer timer;

   public static void Main() {
      timer = new System.Timers.Timer();
      timer.Interval = 5000;

      timer.Elapsed += OnTimedEvent;
      timer.AutoReset = true;
      timer.Enabled = true;

      Console.WriteLine("Press the Enter key to exit anytime... ");
      Console.ReadLine();
   }

   private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {
      Console.WriteLine("Raised: {0}", e.SignalTime);
   }
}
Copy after login

The above is the detailed content of Timer in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template