System.Timers.Timer与System.Windows.Forms.Timer 区别

           根据msdn解释: System.Threading.Timer 是一个简单的轻量计时器,它使用回调方法并由线程池线程提供服务。 不建议将其用于 Windows 窗体,因为其回调不在用户界面线程上进行。 System.Windows.Forms.Timer 是用于 Windows 窗体的更佳选择。 Windows 窗体 Timer 组件是单线程组件,精度限定为 55 毫秒。 如果您需要更高精度的多线程计时器,请使用System.Threading 命名空间中的 Timer 类。 要获取基于服务器的计时器功能,可以考虑使用 System.Threading.Timer,它可以引发事件并具有其他功能。

          简而言之,System.Threading.Timers命名空间中的Timer类主要是针对多线程情况下使用的。而System.Windows.Forms.Timer中的Timer主要是单线程的,即主要是针对某个窗体使用的。举个例子,比如主窗体中可以放一个System.Windows.Forms.Timer动态显示当前时间,每秒更新一次时间显示在右下角.

  private void timer1_Tick(object sender, EventArgs e)
        {
            lblTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
            lblTime.ForeColor = Color.FromArgb(0x2b, 0x47, 0x5b);
        }

而像主窗体中的Socket的通信,则要单独开一个线程处理。例如在发送心调包时就可以用到 System.Threading.Timer来定时发送心跳包了,此时System.Threading.Timer就只在监控心跳包的这个线程上。下面是示例代码:

    /// <summary>
    /// 监听Socket的连接状态
    /// 如果Socket连接断开,则进行重新连接
    /// 如果Socket为连接状态,则发送状态确认包
    /// </summary>
    private void ListenSocCon()
    {
        int interval = 0;
        if (ConfigurationManager.AppSettings["ListenSocTime"] != null)
            {
            int i = 0;
            if (int.TryParse(ConfigurationManager.AppSettings["ListenSocTime"].ToString(), out i))
                {
                interval = 1000 * i;
                }
            else
                {
                interval = 10000;
                }
            }
            //记下日志
            string strOuput = string.Format("开启监听Socket连接线程,时间间隔为:{0}\n",interval.ToString());
            //将信息写入到日志输出文件
            DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
            try
            {

                //使用TimerCallback 委托指定希望 Timer 执行的方法
                TimerCallback timerDelegate = new TimerCallback(tm_ConSock);
                timerConSocket = new System.Threading.Timer(timerDelegate, this, 0, interval);
            }
            catch (Exception e)
            {
                strOuput = string.Format("监听Socket的连接状态出现错误:{0}\n", e.Message);
                //将信息写入到日志输出文件
                DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
            }
        }

    要想更详细的了解System.Threading.Timer和  System.Windows.Forms.Timer请参考MSDN:

  http://msdn.microsoft.com/zh-cn/library/system.threading.timer.aspx;

http://msdn.microsoft.com/zh-cn/library/system.windows.forms.timer.aspx。



转载于:https://www.cnblogs.com/kevinGao/archive/2011/11/04/2236170.html

猜你喜欢

转载自blog.csdn.net/weixin_33948416/article/details/93361109