Ray
Ray

Reputation: 427

How to replace (async) BackgroundWorker with (async) Task.Run (of TPL)?

I've asked a question on how to know when a string of another other party library code changes in my code. I can get access to the string itself at any time. but can't implement INotifyPropertyChanged since it's not my code.

I was offered to use a BackgroundWorker and this solution does work for me! but, I was trying to make sure it is the best solution and got an advise to look at TPL, further researching showed that Task.Run of TPL might be a better solution, as mentioned here for example: Task parallel library replacement for BackgroundWorker? but I couldn't implement it in code.

I am trying to replace this code by Task.Run (Thanks to @a.azemia)

        BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += (s, e) =>
        {
            while (true)
            {
                if (!fc.SecondString.Equals(AnotherPartyLibrary.firstString))
                {
                    fc.SecondString = AnotherPartyLibrary.firstString;
                }
                Thread.Sleep(1000);
            }
        };
    bw.RunWorkerAsync();

I couldn't find any example that fit my scenario and tried to learn from other examples with no success. I need a while loop inside the task and it needs to run asynchronously like the BackgroundWorker does. couldn't find any example with a while loop in the task, so I am not sure of how this can be done.

I've also read that Lambda expressions uses more resources and it was shown in some test that I've seen so I would've liked to avoid Lambda if possible.

Thanks for the help!

Upvotes: 0

Views: 1361

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39132

I still see no real benefit, but here you go:

    private Task T;

    private void Form1_Load(object sender, EventArgs e)
    {

        // ... make sure your string stuff is setup first ...

        T = Task.Run(delegate() { 
            while (true)
            {
                // ... code ...
                System.Threading.Thread.Sleep(1000);
            }
        });
    }    

Upvotes: 0

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

Try this (untested):

public async Task DoWork()
{
   while (true)
  {
      if (!fc.SecondString.Equals(AnotherPartyLibrary.firstString))
      {
         fc.SecondString = AnotherPartyLibrary.firstString;
      }

       await Task.Delay(1000);
  }    
}     

I've used Task.Delay instead of Thread.Sleep as the former does not block a thread while delay is happening. You can invoke this function with await

 await DoWork();

Upvotes: 2

Related Questions