using System;
using System.Timers;
namespace TestTimer
{
internal class Program
{
private static int usingResource = 0;
static int m = 0;
static Timer timerTask = new Timer();
static Timer timerMonitor = new Timer();
static void Main(string[] args)
{
//任务 定时器
timerTask.AutoReset = true;
timerTask.Interval = 1 * 1000;//1秒触发一次
timerTask.Enabled = true;
timerTask.Elapsed += TimerTask_Elapsed;
timerTask.Start();
//监控 定时器
timerMonitor.AutoReset = true;
timerMonitor.Interval = 1 * 1000;//1秒触发一次
timerMonitor.Enabled = true;
timerMonitor.Elapsed += TimerMonitor_Elapsed; ;
timerMonitor.Start();
Console.Read();
}
private static void TimerMonitor_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("m={0}", m);
if (m == 1)
{
Console.WriteLine("set task stop");
timerTask.Stop();
}
}
private static void TimerTask_Elapsed(object sender, ElapsedEventArgs e)
{
if (0 == System.Threading.Interlocked.Exchange(ref usingResource, 1))
{
m = new Random().Next(0, 2);//m只可能为0或1
if (m == 0)
Console.WriteLine("m=0 => {0:HH:mm:ss}", DateTime.Now);
else
{
for (int i = 0; i < 999999999; i++)
{
Console.WriteLine("m=1 => {0:HH:mm:ss}", DateTime.Now);
System.Threading.Thread.Sleep(1000);
}
}
System.Threading.Interlocked.Exchange(ref usingResource, 0);
}
else
{
Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss}, 未取得锁,已退出", DateTime.Now);
}
}
}
}
由上面代码可以得到下面的结果:
没有停止。
有空想其它办法,能中止了写后续