1

I read that backgroundworker will be replaced by task. So i need to ask if there is any difference in performance. And how i will replace my existing code using task instead background worker.

OnLoad

 Timer timer = new Timer();
 timer.Interval = (3000); // * second
 timer.Tick += new EventHandler(timer_Tick);
 timer.Start();

private void timer_Tick(object sender, EventArgs e)
    {
        if (!backgroundWorker.IsBusy)
             backgroundWorker.RunWorkerAsync();  
    }

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
     //Here i'm running my code
    }

Every 3 seconds my background worker runs a specfic routine inside my main. How can i replace it with task?

Community
  • 1
  • 1
M.Doe
  • 41
  • 6
  • 1
    BackgroundWorker is there to stay, if you know how to use it, just use it. Hoever if you want to try the Task approuch, I suggest you read about, try it, and ask a more specific question. – Poul Bak Aug 16 '18 at 00:47
  • BackgroundWorker still in use and it is good for tasks that do not tangle (like when you need to stop task until another one finish). You can read this for more details [https://stackoverflow.com/questions/1506838/backgroundworker-vs-background-thread](https://stackoverflow.com/questions/1506838/backgroundworker-vs-background-thread) – Nano Aug 16 '18 at 01:19

1 Answers1

-1

Instead of the backgroundWorker event, write a method. Then in your timer_tick event write something like this:

private async void timer_Tick(object sender, EventArgs e)
    {
        await Task.Run(() => 
        {
            YourMethod();
        });
    }

Here is a link to more on the subject;

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
  • Is there any better(quicker) in performance or are both the same? – M.Doe Aug 16 '18 at 06:58
  • I'm not an expert in performance but I think they're pretty close to each other and the choice depends on other Things. – Poul Bak Aug 16 '18 at 20:02
  • Background worker handles more than just running a task. It also handles communication between the background task and the UI thread. Also not sure why you're making the method async void to just await the running task. – MikeJ Oct 21 '20 at 14:40