Winform基于多线程实现每隔1分钟执行一段代码
本文实例讲述了Winform基于多线程实现每隔1分钟执行一段代码的方法,分享给大家供大家参考。具体实现方法如下:
1.定义相关的类Timer.cs,代码如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading;
namespaceSMIS2013.DSS.Monitor { publicclassMyTimer { publicdelegatevoidElapsed();//定义委托 publiceventElapsedOnElapsed;
privatelong_Interval=1000; publiclongInterval { get{return_Interval;} set{_Interval=value;} }
privatebool_IsStart=false; privateThread_TimerThread; publicvoidStart() { if(_IsStart) return;
_IsStart=true;
_TimerThread=newThread(newThreadStart(DoTimer)); _TimerThread.Start(); }
publicvoidStop() { try { if(!_IsStart) return;
_IsStart=false;
_TimerThread.Abort(); } catch(Exceptione) {} }
privatevoidDoTimer() { try { intlast=Environment.TickCount; while(_IsStart) { if(Environment.TickCount-last>_Interval) { if(OnElapsed!=null) OnElapsed();
last=Environment.TickCount; } Thread.Sleep(100); }
} catch(Exceptione) {} }
} }