线程,定时启动

做个备忘录

有个项目,要求程序在启动后定时(每30s)启动一次扫描程序,用了一个timer线程。

可是奇怪的是,这个线程启动一次或者数次之后就停止了。

最后终于搞清楚了,线程必须保持引用,否则会被回收,应该设为全局变量。

 private void frmMain_Load(object sender, EventArgs e)
{

   TimerCallback timecall = new TimerCallback(SendSubscribedCarsInfo);
       //这样定义的变量会被回收

   System.Threading.Timer   timeQueryGps = new System.Threading.Timer(timecall, null, 0, 2000);
           

}

应该改为这样:

System.Threading.Timer   timeQueryGps;

private void frmMain_Load(object sender, EventArgs e)
{

   TimerCallback timecall = new TimerCallback(SendSubscribedCarsInfo);
       //这样定义的就正常运行了

   timeQueryGps = new System.Threading.Timer(timecall, null, 0, 2000);
           

}

posted @ 2011-06-28 09:25  肖湘  阅读(653)  评论(3编辑  收藏  举报