利用System.Threading.Timer 实现定时执行

来源:互联网 发布:hm有淘宝旗舰店吗 编辑:程序博客网 时间:2024/05/17 04:47

直接使用System.Threading.Timer
示例代码:
在程序中调用Start() ,定时器到指定时间时就会弹出对话框提示!

 

 

 

  1. private System.Threading.Timer timer; 
  2.         private bool _status = false
  3.         private void Start() 
  4.         { 
  5.             System.Threading.TimerCallback timerCallback = new System.Threading.TimerCallback(_clearTimeoutLocks); 
  6.             timer = new System.Threading.Timer(timerCallback, this, 10000, 10000); 
  7.         } 
  8.         private void _clearTimeoutLocks(object caller) 
  9.         { 
  10.             if (_status) 
  11.                 return
  12.             else 
  13.             { 
  14.                 _status = true
  15.                 try 
  16.                 { 
  17.                     //do something here  
  18.                     MessageBox.Show("is timer!"); 
  19.                 } 
  20.                 catch (Exception err) { } 
  21.                 finally 
  22.                 { 
  23.                     _status = false
  24.                 } 
  25.             } 
  26.         }

        _status 是我自己定义的一个控制锁, 是为了防止第一次没有执行完的情况下第二次又进来

原创粉丝点击