ASP.NET 定时器回调方法的重入
程序员文章站
2023-11-21 21:14:22
话不多说,请看代码:
using system;
using system.collections.generic;
using system.text;...
话不多说,请看代码:
using system; using system.collections.generic; using system.text; namespace net.mst.sixth.reenter { class reenter { //用来造成线程同步问题的静态成员 private static int testint1=0; private static int testint2 = 0; private static object locko = new object(); static void main(string[] args) { console.writeline("system.timers.timer 回调方法重入测试:"); timerstimerreenter(); //这里确保已经开始的回调方法有机会结束 system.threading.thread.sleep(2 * 1000); console.writeline("system.threading.timer 回调方法重入测试:"); threadingtimerreenter(); console.read(); } /// <summary> /// 展示system.timers.timer的回调方法重入 /// </summary> static void timerstimerreenter() { system.timers.timer timer = new system.timers.timer(); timer.interval = 100; //100毫秒 timer.elapsed += timerstimerhandler; timer.start(); system.threading.thread.sleep(2 * 1000); //运行2秒 timer.stop(); } /// <summary> /// 展示system.threading.timer的回调方法重入 /// </summary> static void threadingtimerreenter() { //100毫秒 using (system.threading.timer timer = new system.threading.timer (new system.threading.timercallback(threadingtimerhandler), null, 0, 100)) { system.threading.thread.sleep(2 * 1000); //运行2秒 } } /// <summary> /// system.timers.timer的回调方法 /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private static void timerstimerhandler(object sender,eventargs args) { lock (locko) { console.writeline("测试整数:" + testint1.tostring()); //睡眠10秒,保证方法重入 system.threading.thread.sleep(300); testint1++; console.writeline("自增1后测试整数:" + testint1.tostring()); } } /// <summary> /// system.threading.timer的回调方法 /// </summary> /// <param name="state"></param> private static void threadingtimerhandler(object state) { lock (locko) { console.writeline("测试整数:" + testint2.tostring()); //睡眠10秒,保证方法重入 system.threading.thread.sleep(300); testint2++; console.writeline("自增1后测试整数:" + testint2.tostring()); } } } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
下一篇: 常见的KPI评估指标知识