Run timer in background thread

2019-05-29 03:44发布

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();

Then in the backgroundworker_dowork method i have this:

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

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

Thanks

7条回答
欢心
2楼-- · 2019-05-29 04:13
using System.Timers;
using System.Threading.Tasks;
.
.
.
var timer = new Timer(250);
.
.
.
private void Initialize()
{
    timer.Elapsed += (o, s) => Task.Factory.StartNew(() => OnTimerElapsed(o, s));
    timer.Start();
}
.
.
.
private void OnTimerElapsed(object o, ElapsedEventArgs s)
{
    //Do stuff
}

You can also get rid of the OnTimerElapsed parameters "o" and "s" if you want.

查看更多
登录 后发表回答