在后台线程运行定时器 [英] Run timer in background thread

查看:199
本文介绍了在后台线程运行定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林寻找一种方式来使用一个线程的背景资料中的一个System.Windows.Forms.Timer。我CAM有很多的麻烦就来启动和后台线程内停止。这是我在做什么:

Im looking for a way to use a System.Windows.Forms.Timer within a backgrounder thread. I cam having a lot of trouble getting it to start and stop within the background thread. This is what i am doing:

private System.Windows.Forms.Timer chkTimer = new System.Windows.Forms.Timer();



然后在backgroundworker_dowork方法,我有这样的:

Then in the backgroundworker_dowork method i have this:

     chkTimer.Interval = 2000;
     chkTimer.Tick += new EventHandler(chkTimer_Tick);
     chkTimer.Start();

在蜱方法我有定时器相关的代码,但它不会出于某种原因运行。如果我宣布在上面的UI线程,它的工作原理。可以someoine请帮我启动后台线程内的计时器?我不想用这么System.Timers请不要认为

In the Tick method i have the timer related code but it will not run for some reason. If i declare the above in the ui thread, it works. Can someoine please help me start the timer within the background thread? I do not want to use System.Timers so please dont suggest that

感谢

推荐答案

我不会完全使用定时器,其微胖。从我读你想有两个线程,UI和后台线程。

I would not use a timer altogether, its extra baggage. From what I read you want to have two threads, the UI and the background thread.

所以,有后台线程管理区间,而不是定时器。

So, have the background thread manage the interval instead of the timer.

的伪代码:

YourFileChecker checker = new YourFileChecker();
checker.CheckInterval = 60000; //milliseconds, the background thread will manage the interval

System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(checker.Check));
t.Start();



然后让检查方法做这样的事情:

Then have the Check method do something like this:

 while(!_Stop)
 {
      //Do your work here

      //Wait the specified interval before checking again...
      Thread.Sleep(_CheckInterval);
 }



后台线程现在只是不断检查,直到被告知(信号),停止。然后,你不需要计时器,因为在所有的线程管理的间隔时间。

The background thread now just keeps checking until it is told (signaled) to stop. Then you don't need the timer at all because the thread is managing the interval.

这篇关于在后台线程运行定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆