Run timer in background thread

Greg picture Greg · Jun 22, 2011 · Viewed 14.5k times · Source

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

Answer

user1172282 picture user1172282 · Jan 4, 2013
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.