C#中三种Timer计时器的详细用法

Introduction

In C#, there are three types of timers that can be used for various timing tasks. These timers are System.Timers.Timer, System.Windows.Forms.Timer, and System.Threading.Timer. Each timer has its unique features and usage scenarios. In this article, we will explore in detail the usage of these timers and understand how they can be effectively utilized in C# applications.

System.Timers.Timer

System.Timers.Timer is a timer that raises an event at regular intervals. It is available in the System.Timers namespace. The timer can be started, stopped, and reset as required. It is typically used in scenarios where you want to perform a specific task repeatedly after a fixed interval of time.

Using System.Timers.Timer

To use the System.Timers.Timer, you need to first create an instance of the timer class and set the desired interval. Then, you can subscribe to the Elapsed event, which will be raised each time the interval elapses. Here is an example of using System.Timers.Timer:

using System;

using System.Timers;

class Program

{

static void Main()

{

System.Timers.Timer timer = new System.Timers.Timer();

timer.Interval = 1000; // 1 second

timer.Elapsed += TimerElapsed;

timer.Start();

Console.WriteLine("Press any key to stop the timer.");

Console.ReadKey();

timer.Stop();

}

static void TimerElapsed(object sender, ElapsedEventArgs e)

{

Console.WriteLine("Timer elapsed at {0}", e.SignalTime);

}

}

In this example, we create a timer with an interval of 1 second and subscribe to the TimerElapsed method, which will be called each time the timer elapses. The timer is started and will continue to raise events until it is stopped.

System.Windows.Forms.Timer

System.Windows.Forms.Timer is a timer specifically designed for Windows Forms applications. It runs on the UI thread and raises the Tick event at regular intervals. It is commonly used to update the UI or perform other tasks that require access to UI elements.

Using System.Windows.Forms.Timer

Using System.Windows.Forms.Timer is straightforward. You can drag and drop it from the toolbox onto your Windows Forms designer. Alternatively, you can create an instance of the timer programmatically. Once the timer is added, you can set the interval and subscribe to the Tick event. Here is an example of using System.Windows.Forms.Timer:

using System;

using System.Windows.Forms;

class MainForm : Form

{

private Timer timer;

public MainForm()

{

timer = new Timer();

timer.Tick += TimerTick;

timer.Interval = 1000; // 1 second

// Other UI initialization code

}

protected void TimerTick(object sender, EventArgs e)

{

// Perform UI update or other tasks

}

}

In this example, we create an instance of the timer in the constructor of the MainForm class and set the interval to 1 second. We then subscribe to the TimerTick event, which will be raised every 1 second. You can perform any required UI update or other tasks within the event handler.

System.Threading.Timer

System.Threading.Timer is a timer that runs on a separate thread. It is available in the System.Threading namespace and is commonly used in multithreaded scenarios. The timer raises the TimerCallback event at specified intervals and executes the callback method on a thread pool thread.

Using System.Threading.Timer

To use System.Threading.Timer, you need to create an instance of the timer class and provide a TimerCallback delegate that specifies the method to be executed at each interval. You can also set the initial delay and the interval. Here is an example of using System.Threading.Timer:

using System;

using System.Threading;

class Program

{

static void Main()

{

TimerCallback callback = TimerCallbackMethod;

Timer timer = new Timer(callback, null, 0, 1000); // 1 second

Console.WriteLine("Press any key to stop the timer.");

Console.ReadKey();

timer.Dispose();

}

static void TimerCallbackMethod(object state)

{

Console.WriteLine("Timer callback executed at {0}", DateTime.Now);

}

}

In this example, we create a TimerCallback delegate that points to the TimerCallbackMethod. We then create an instance of the timer with an initial delay of 0 and an interval of 1 second. The TimerCallbackMethod will be executed on the thread pool thread at each interval.

Conclusion

In this article, we explored the three types of timers available in C# – System.Timers.Timer, System.Windows.Forms.Timer, and System.Threading.Timer. Each timer has its own unique features and is suitable for different scenarios. By understanding the usage of these timers, you can effectively handle timing tasks in your C# applications. Remember to choose the appropriate timer based on your specific requirements and architectural considerations.

后端开发标签