C#四种定时器的用法
日常项目开发中,很多时候都需要用到定时器来处理一些问题,那么c#中各种定时器应该怎么用呢?下面来简单介绍下C#中4种定时器的使用方法说明:
第一种定时器,System.Windows.Forms.Timer
使用方法如下:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();//创建定时器
timer.Tick += new EventHandler(timer1_Tick);//事件处理
timer.Enabled = true;//设置启用定时器
timer.Interval = 1000;//执行时间
timer.Start();//开启定时器
/// <summary>
/// 定时器事件处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
timer.Stop();//停止定时器
timer.Tick -= new EventHandler(timer1_Tick);//取消事件
timer.Enabled = false;//设置禁用定时器
}
第二种定时器,System.Threading.Timer
使用方法如下:
System.Threading.Timer timer;
timer = new System.Threading.Timer(new TimerCallback(timerCall), this, 3000, 0);//创建定时器
/// <summary>
/// 事件处理
/// </summary>
/// <param name="obj"></param>
private void timerCall(object obj)
{
timer.Dispose();//释放定时器
}
第三种定时器,System.Timers.Timer
使用方法如下:
System.Timers.Timer timer = new System.Timers.Timer(1000);//创建定时器,设置间隔时间为1000毫秒;
timer.Elapsed += new System.Timers.ElapsedEventHandler(theout); //到达时间的时候执行事件;
timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
timer.Enabled = true;//需要调用 timer.Start()或者timer.Enabled = true来启动它,
timer.Start();//timer.Start()的内部原理还是设置timer.Enabled = true;
/// <summary>
///执行事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
public void theout(object source, System.Timers.ElapsedEventArgs e)
{
timer.Elapsed -= new System.Timers.ElapsedEventHandler(theout); //取消执行事件;
timer.Enabled = false;//禁用
timer.Stop();//停止
}
第四种定时器,System.Windows.Threading.DispatcherTimer(WPF中的定时器)
使用方法如下:
private static System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();//创建定时器
timer.Tick += new EventHandler(timer_out);//执行事件
timer.Interval = new TimeSpan(0, 0, 0, 1);//1s执行
timer.IsEnabled = true;//启用
timer.Start();//开启
/// <summary>
///执行事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
public static void timer_out(object sender, EventArgs e)
{
timer.Tick -= new EventHandler(timer_out);//取消执行事件;
timer.IsEnabled = false;//禁用
timer.Stop();//停止
}
注意事项
1.DispatcherTimer是运行在UI线程上的,其好处是可以在定时事件中修改UI元素,其它三种定时器是运行在独立的线程上的,与UI线程无关。
2.如果需要修改UI控件,则必须委托给调度器this.Dispatcher进行,不然的话会提示界面资源被其他线程所拥有而无法更新界面。