日期:2014-05-19  浏览次数:20659 次

在C#里关于定时器类就有3个,他们有什么本质的区别?
在C#里关于定时器类就有3个      
1.定义在System.Windows.Forms里      
2.定义在System.Threading.Timer类里
3.定义在System.Timers.Timer类里    

System.Windows.Forms.Timer是应用于WinForm中的,它是通过Windows消息机制实现的,类似于VB或Delphi中的Timer控件,内部使用API     SetTimer实现的。它的主要缺点是计时不精确,而且必须有消息循环,Console     Application(控制台应用程序)无法使用。      
   
System.Timers.Timer和System.Threading.Timer非常类似,它们是通过.NET     Thread     Pool实现的,轻量,计时精确,对应用程序、消息没有特别的要求。System.Timers.Timer还可以应用于WinForm,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码。  
//*************************************************************
既然说forms里面的timer控件完全可以用System.Timers.Timer来替代
那我的问题出在哪里了?
我用MapXtreme+vs2005   做GPS模拟定位
在System.Timers.Timer类下程序时有错误的(也许是MapXtreme里面的类有线程不安全的)
然而在Forms.Timer类下程序是可以跑起来的
郁闷的紧
不晓得问题出在哪里?

//*************************************************************


------解决方案--------------------
使用System.Timers.Timer类
System.Timers.Timer t = new System.Timers.Timer(10000);//实例化Timer类,设置间隔时间为10000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
public void theout(object source, System.Timers.ElapsedEventArgs e)
{
MessageBox.Show( "OK! ");
}

在使用时要
System.Timers.Timer t
如只timer t

会默认System.Windows.Forms.timer
------解决方案--------------------
推荐使用System.Threading.Timer
详细的解答见clr via c#一书,中文版 500页.
------解决方案--------------------
反编译这几个类。

都是调用Win32 API中的SetTimer函数函数。本质一样的。
System.Windows.Forms.Timer使用了一个内部窗口实现ui的消息截取。再post给Form.
那两个的侧重点不一样。

------解决方案--------------------
定义在System.Windows.Forms里那个是,主线程中同步处理的
其他是处理函数在线程池线程上执行,属于异步处理。关键是同步异步的区别。