日期:2014-05-20  浏览次数:20742 次

关于Timer和线程的问题,各位高手帮我看看了。
我需要实现定时执行某项操作的功能,因为这个操作很费时,所以我想使用线程来完成,可是在测试出现很奇怪的问题,每次到指定时间就会循环执行好多次。
private   void   timeUpdate_Tick(object   sender,   System.EventArgs   e)
{
              DateTime   t   =   DateTime.Now   ;
              string   s       =   t.ToLongTimeString   ();
              this.label1.Text   =   s;
              string   fistTime   =   opIni.IniReadValue( "updatefilepath ", "StarTime ");
           
              if(DateTime.Now.ToString( "HH:mm:ss ")==   fistTime   )
                {
        //执行更新程序
                            Thread   threadTest   =   new   Thread(new   ThreadStart(test));
          threadTest.IsBackground   =   true;
          threadTest.Start();
          // this.test();
}

}
private   void   test()
{
//这里执行了一些连接数据库查找数据的操作

}
//这个是加载时的Timer设置
private   void   frmAutoUpdate_Load(object   sender,   System.EventArgs   e)
{
this.timeUpdate   .Tick   +=   new       System.EventHandler(this.timeUpdate_Tick   );
timeUpdate.Interval=1000;
timeUpdate.Start();
}
如果不用线程序,直接到时间执行test()就会成功。如果用线程就会重复执行,而且在填充DataSet时间提示找不到表0.
各位高手指点一下小弟了。

------解决方案--------------------
重复执行?
可能是这句有问题吧
if(DateTime.Now.ToString( "HH:mm:ss ")== fistTime )

你调一下
------解决方案--------------------
在线程threadTest.Start()后面用Thread.sleep(2000)
,否则你那样运行会多次判断DateTime.Now.ToString( "HH:mm:ss ")== fistTime