using System;
using System.Threading;
using System.Timers;
class Program
{
static void Main(string[] args)
{
bool endFlag=false;
System.Timers.Timer t1 = TimerHelper.CreateTimer(() => { Console.WriteLine("1111"); });
t1.Start();
System.Timers.Timer t2 = TimerHelper.CreateTimer(() => { Console.WriteLine("2222"); });
t2.Start();
new Thread(()=>
{
TimerHelper ti = new TimerHelper();
ti.UpdateStartTime();
while (true)
{
if (ti.IsTimeOut(10000))
{
t1.Stop();
Console.WriteLine("t1,End");
break;
}
}
}).Start();
new Thread(() =>
{
TimerHelper ti = new TimerHelper();
ti.UpdateStartTime();
while (true)
{
if (ti.IsTimeOut(10000))
{
t2.Stop();
Console.WriteLine("t2,End");
endFlag = true;
break;
}
}
}).Start();
while(true)
{
if(endFlag)
{
break;
}
}
Console.WriteLine("示例结束");
Console.ReadKey();
}
public class TimerHelper
{
DateTime startTime =DateTime.Now;
public void UpdateStartTime()
{
startTime = DateTime.Now;
}
public bool IsTimeOut(int timeOut)
{
return (DateTime.Now.Subtract(startTime).TotalMilliseconds > timeOut);
}
static public System.Timers.Timer CreateTimer(Action action, int interval=1000, bool autoReset=true)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += (sender, e) => action();
timer.Interval = interval;
timer.AutoReset = autoReset;
return timer;
}
}
}
C# 执行定时功能与超时功能Helper
于 2023-05-11 09:53:47 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)