0

I am using a background worker and reporting the progress to a progress bar. In BackgroundWorker DoWork Event I am calling few methods on completion of each method. I am literally updating the progress value which works fine.

But when I call an async method in my DoWork, after call ends, I am updating the progress value with my desired value - but it throws to me an exception that says:

"Operation has already been completed" this occurs only when i call an "async method".

This is my code:

LoginBackgroundThreadReport(20, "Requesting Token");

long _StatusCode = await RequestNewToken();

LoginBackgroundThreadReport(30, "Configuring Device");   


//LoginBackgroundThreadReport method    
private void LoginBackgroundThreadReport(int pValue, string pMessage, long pStatusCode = 0)
{
    object[] _arr = new object[2];
    _arr[0] = pMessage;
    _arr[1] = pStatusCode;
    LoginBackgroundWorker.ReportProgress(pValue, _arr);
}

Here "Requesting Token" is displayed but the "configure device" fails, as I am updating value 30 after I call async method that is updating my progress value automatically to 100.

Sam
  • 7,252
  • 16
  • 46
  • 65
  • 1
    Why do you need to call `RequestNewToken` async? You're already on a separate thread from the GUI and you only need to report the progress when the step is done. – John Willemse Jul 03 '14 at 07:46
  • Which method is throwing the exception? – Yuval Itzchakov Jul 03 '14 at 08:29
  • RequestNewToken is a method which is in my common class which is used in multiple places so there is no point that i am going to modify it so just used it the same way. – user3721395 Jul 03 '14 at 12:59
  • Anyways found a solution finally Here is the link i referred http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously – user3721395 Jul 03 '14 at 13:01
  • Do you actually have long running CPU bound work, or are the only long running operations that you have IO bound? If so, just remove the BGW and run the code right in the UI thread and you'll be fine, thanks to the asynchrony. – Servy Jul 09 '14 at 16:01

1 Answers1

1

I recommend that you replace BackgroundWorker with Task.Run, and use IProgress<T>/Progress<T> for progress updates.

I have a blog post that compares progress reporting with BGW to that used by Task.Run.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810