JSON JSON - 5 months ago 20
C# Question

What is the point of backgroundworker.WorkerReportsProgress

Can someone please explain the purpose of this

boolean value?

Why not just allow background worker to report progress all the time?

In my initial testing I couldn't find a huge impact on performance, so the setting seems redundant.

I guess the reason I am asking is I want to avoid misusing it if there is some impact on perfromance, and to see if there is something obvious that I am missing.


The purpose of that boolean value is to raise an exception if you call ReportProgress (the other overload calls this one as well) on the instance of the BackgroundWorker.

public void ReportProgress(int percentProgress, object userState)
    if (!this.WorkerReportsProgress)
        throw new InvalidOperationException(SR.GetString("BackgroundWorker_WorkerDoesntReportProgress"));
    ProgressChangedEventArgs progressChangedEventArgs = new ProgressChangedEventArgs(percentProgress, userState);
    if (this.asyncOperation != null)
        this.asyncOperation.Post(this.progressReporter, progressChangedEventArgs);

With ILSpy you can do an analyze on a property and its backing field to see where it is used and it turns out above method is the only place.

decompile of BackgroundWorker in ILSpy

The why is a bit speculative but I guess the component designers wanted to make sure to blow up at runtime if you call ReportProgress in DoWork without setting WorkerReportProgress to true. It looks like they had great plans with it, but it didn't make it in the final implementation.