我们知道,System.Threading.Timer可以定时每隔一段时间执行一次任务。
不知道大家有没有想过,如果任务执行时间比较长,Interval到期之后会发生什么;是会结束当前的线程,还是会重新启动一个线程?
下面代码我们模拟一下,任务执行时间5s, Interval=2s的运行情况:
using System;
using System.Timers;
namespace TimerTest2
{
class Program
{
static void Main(string[] args)
{
Timer t1 = new Timer();
t1.Interval = 2000;
t1.Elapsed += ct_Elapsed;
t1.Start();
Console.ReadLine();
}
static void ct_Elapsed(object sender, ElapsedEventArgs e)
{
int i = 1;
// 执行 500ms * 10 = 5s
while (i <= 10)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " - Thread:" + System.Threading.Thread.CurrentThread.ManagedThreadId + " =