多线程编程(2.Timer)

3/8/2017来源:ASP.NET技巧人气:1817

Threading.Timer

internal sealed class UnSafelTimer { PRivate static Timer timer; private static object unsafel_lock = new object(); private static int count = 0; private static Stopwatch watch = new Stopwatch(); private static void ExcuteMethod(object state) { //不是后台线程 Thread.CurrentThread.IsBackground = true; int temp; lock (unsafel_lock) { count++; temp = count; } if (temp == 10) { timer.Dispose(); watch.Stop(); } if (temp < 10) Console.WriteLine("NOW:{0}", temp); else Console.WriteLine("NOW:{0},-------Timer已经耗时{1}毫秒了", temp, watch.ElapsedMilliseconds); //模拟花10秒时间 Thread.Sleep(1000); } public static void Start() { watch.Start(); //2秒钟后每次间隔10毫秒就启动定时器 timer = new Timer(ExcuteMethod, null, 1000, 10); } }

Timer.Timer

internal sealed class SafelTimer { private static System.Timers.Timer timer; private static object unsafel_lock = new object(); private static int count = 0; private static Stopwatch watch = new Stopwatch(); public static void Start() { timer = new System.Timers.Timer(); timer.Interval = 10;//每隔10毫秒执行 timer.Elapsed += ExcuteMethod; timer.Start(); } private static void ExcuteMethod(object sender, System.Timers.ElapsedEventArgs e) { Thread.CurrentThread.IsBackground = true; int temp; lock (unsafel_lock) { count++; temp = count; } if (temp == 10) { timer.Dispose(); watch.Stop(); } if (temp < 10) Console.WriteLine("NOW:{0}", temp); else Console.WriteLine("NOW:{0},-------Timer已经耗时{1}毫秒了", temp, watch.ElapsedMilliseconds); //模拟花10秒时间 Thread.Sleep(1000); } }