Reputation: 3053
In my application I need a background thread that contacts a server every N seconds...
I made it in this way:
Task.Factory.StartNew (() => {
while(true)
{
Thread.Sleep (10000);
...do my stuff...
}
});
This solution works fine but I need to know if there is a better one. (for example: is Task.Delay(10000) a better solution?)
Thanks a lot!
Upvotes: 0
Views: 4625
Reputation: 2998
If you need to use the UI you could use the example of DaveDev, otherwise the example below would also work. If you want to use UI in this example you have to use the Invoke
or BeginInvoke
methods of the controls.
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Timer stateTimer = new Timer(CheckStatus);
// Change the period to every 1/2 second.
stateTimer.Change(0, 500);
}
public static void CheckStatus(Object stateInfo) {
...
}
}
I think it is important to know why not to use Thread.Sleep
in this case. If you use sleep it locks up the thread. If you use a timer then the thread can be used to do other tasks in the meantime.
Upvotes: 2
Reputation: 42175
_timer = new DispatcherTimer();
_timer.Tick += timer_Tick;
_timer.Interval = new TimeSpan(0, 0, 0, 1);
_timer.Start();
private void timer_Tick(object sender, EventArgs e)
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, a) =>
{
//do your stuff
};
backgroundWorker.RunWorkerAsync();
}
Upvotes: 0