"Operation already completed" error when using Progress Bar
To elaborate on the comment from dkozl:
It is possible that the async
is causing the problem. There's nothing in the code you posted that would cause an issue, but of course the code example you posted is far from complete.
If you have an await
statement in your processMovie_DoWork()
method (which is the usual reason one makes a method async
), then the method will execute only as far as the point of the first await
statement, and then it will exit.
As far as the BackgroundWorker
class is considered, this marks the end of the work. It has no way to know that some continuation would be called. Thus, when you call the ReportProgress()
method, the operation has in fact completed, making the call to ReportProgress()
illegal.
You have a couple of options here:
- Get rid of the
await
statements and perform those operations synchronously. Preferably by calling the synchronous version of the API. - Get rid of the
BackgroundWorker
and just call yourprocessMovie_DoWork()
method directly (albeit likely renamed to something else). In this case, instead of calling theReportProgress()
method, you'd just update theCurrentProgress
property directly.
IMHO, the second option is much preferable. You can simply await
your processMovie_DoWork()
method, and avoid all the hassle of dealing with BackgroundWorker
.
I just encountered this problem trying to poll status from a Web API using Background Worker.
I resolved this by removing async
and changing the await
operator to Task.Wait()
and it worked perfectly.
Here is my Code in place of "// Do stuff like calling API
" :
var task = JobManager.GetJobStatus(id);
task.Wait();
var status = task.Result;
I hope this helps somebody else. I am sure you got over this issue.