I'm little confused with all of this. I need to create a lifetime method inside my application which it will Communicate with an asp net web service and it will returns me some results. As long my application is running, this method will never stop.
Method-1 creating an Task.
t=Task.Run(()=>ffAsync());
async void ffAsync()
{
while (true)
{
await Task.Delay(5000);
Console.WriteLine("Reading from server every 5 seconds");
}
}
Method2 using background worker
Timer t = new Timer();
t.Interval = 5000;
timer1.Enabled = true;
timer1.Tick += new
System.EventHandler(OnTimerEvent);
private void OnTimerEvent(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
Method-3 using Thread
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
while(true)
{
Thread.Sleep(5000);
Console.WriteLine("Run every 5 seconds");
}
}).Start();
Which method is more effective in my case? Also another optimization question, is it better to use a task.delay(x),Thread.Sleep(x) for running my loop every x seconds, or creating a timer (as my seconds example) which it will trigger my event every x seconds?