首页 > 学院 > 开发设计 > 正文

多线程编程(2.Timer)

2019-11-06 06:02:29
字体:
来源:转载
供稿:网友

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); } }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表