JSON JSON - 3 months ago 13
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.

Answer

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);
        return;
    }
    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.

Comments