Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task vs Thread vs background worker for a lifetime method

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?

like image 485
Dim Avatar asked Sep 03 '25 15:09

Dim


1 Answers

Which method is more effective in my case?

None of these are right. All of them make background workers, which is wrong for IO bound tasks.

You would not hire a worker to do nothing but sleep 23 hours 59 minutes and 59.9999 seconds a day and do 0.0001 seconds of work. So you should not hire a thread to do that either.

Asynchronous IO should be written to use asynchrony and should run on whatever context needs the result of the IO. Do not use Task.Run. Use asynchronous IO inside the loop!

is it better to use a Task.Delay, Thread.Sleep or creating a Timer?

Do not hire a worker and then make them sleep. Either use a delay, or make a timer. Pick which ever one works better for your program structure. But the important thing is all of the workflow should be done on the main thread and the IO calls must be asynchronous.

like image 106
Eric Lippert Avatar answered Sep 05 '25 14:09

Eric Lippert