ilay zeidman
ilay zeidman

Reputation: 2814

Progress<T> doesn't have Report function

I have windows form app this is my code:

  private async void btnGo_Click(object sender, EventArgs e)
    {
        Progress<string> labelVal = new Progress<string>(a => labelValue.Text = a);
        Progress<int> progressPercentage = new Progress<int>(b => progressBar1.Value = b);

       // MakeActionAsync(labelVal, progressPercentage);
        await Task.Factory.StartNew(()=>MakeActionAsync(labelVal,progressPercentage));
        MessageBox.Show("Action completed");
    }

    private void MakeActionAsync(Progress<string> labelVal, Progress<int> progressPercentage)
    {
            int numberOfIterations=1000;
            for(int i=0;i<numberOfIterations;i++)
            {
                Thread.Sleep(10);
                labelVal.Report(i.ToString());
                progressPercentage.Report(i*100/numberOfIterations+1);
            }
    }

I get compilation error that "System.Progress' does not contain a definition for 'Report' and no extension method 'Report' accepting a first argument of type 'System.Progress' could be found (are you missing a using directive or an assembly reference?)"

but If you look at Progress class:

public class Progress<T> : IProgress<T>

and the interface IProgress has function Report:

  public interface IProgress<in T>
{
    // Summary:
    //     Reports a progress update.
    //
    // Parameters:
    //   value:
    //     The value of the updated progress.
    void Report(T value);
}

What am I missing?

Upvotes: 30

Views: 5274

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Progress<T> implemented the method with explicit interface implementation. So you can't access the Report method with instance of type Progress<T>. You need to cast it to IProgress<T> to use Report.

Just change the declaration to IProgress<T>

IProgress<int> progressPercentage = new Progress<int>(b => progressBar1.Value = b);

Or use a cast

((IProgress<int>)progressPercentage).Report(i*100/numberOfIterations+1);

I prefer former version, latter is awkward.

Upvotes: 37

Patrick Hofman
Patrick Hofman

Reputation: 156948

As shown in the documentation, that method is implemented using a explicit interface implementation. That means it is hidden if you don't use the interface to access the method.

Explicit interface implementations are used to make some properties and methods visible when referencing to the interface, but not in any derived class. So you only 'see' them when you use IProgress<T> as your variable type, but not when using Progress<T>.

Try this:

((IProgress<string>)progressPercentage).Report(i*100/numberOfIterations+1);

Or when you only need to reference properties and methods available in the interface declaration:

IProgress<string> progressPercentage = ...;

progressPercentage.Report(i*100/numberOfIterations+1);

Upvotes: 6

Related Questions