在Global.asax,cs中实现一个定时器,做一些事情,我想是每一秒检查一下,如果有情况,就做一件事件。但是做这件事情有可能需要好几秒,这时就不要开始新的动作,等他做完手头的事,再过一秒再检测。
我用了 new System.Threading.Timer(cacheMonitorTimer_Timer, null, 1000, 1000);
但我发现这个东西是同步的,如果我在cacheMonitorTimer_Timer中做事情时间太长,会把网站卡死。
有没有高手弄过类似的问题?
最终没有使用timer,因为timer最终还是在主线程上,会阻塞主线程。new了一个thread,里面是一个永真循环,然后里面用thread.sleep来控制间隔时间。
1、做这个事的时候,给全局变量赋值isRunning=true。结束后赋值isRunning=false。
2、每一秒检查时,判断isRunning=false,才去做。
3、这个事可以在别的线程里面做。
4、就算在别的线程做,你也要考虑别占用太多的资源,资源是共用的(CPU\内存\IO等等)
开个新线程来做,等待回调,做事情的时候就禁用当前timer,做完回调的时候在启用,1s后又会执行。
这种需求应该另外开一个Windows Services吧?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { //过一秒就检测的定时器要开始了 System.Timers.Timer t = new System.Timers.Timer(); t.Interval = 1000; t.Elapsed += t_Elapsed; t.Start(); } static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { System.Timers.Timer t = (System.Timers.Timer)sender; try { //既然你要工作一段时间,那你就开始做吧 t.Stop(); //做你需要做的事 //做远了那我们就再继续吧 t.Start(); } catch (Exception) { if (t != null) { t = null; t.Elapsed -= t_Elapsed; } } } } }