Progress <T>没有报告功能

ila*_*man 14 c# winforms async-await

我有windows form app这是我的代码:

  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);
            }
    }
Run Code Online (Sandbox Code Playgroud)

我得到编译错误,"System.Progress"不包含'Report'的定义,并且没有扩展方法'Report'接受类型'System.Progress'的第一个参数可以找到(你是否缺少using指令或程序集参考?)"

但是 如果你看一下Progress类:

public class Progress<T> : IProgress<T>
Run Code Online (Sandbox Code Playgroud)

和IProgress接口有功能报告:

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

我错过了什么?

Sri*_*vel 19

Progress<T>显式接口实现实现了该方法.因此,您无法使用Report类型实例访问该方法Progress<T>.你需要把它投射IProgress<T>使用Report.

只需将声明更改为 IProgress<T>

IProgress<int> progressPercentage = new Progress<int>(b => progressBar1.Value = b);
Run Code Online (Sandbox Code Playgroud)

或使用演员

((IProgress<int>)progressPercentage).Report(i*100/numberOfIterations+1);
Run Code Online (Sandbox Code Playgroud)

我更喜欢以前的版本,后者很尴尬.


Pat*_*man 6

文档中所示,该方法是使用显式接口实现来实现的。这意味着如果您不使用接口访问该方法,它就会被隐藏。

显式接口实现用于使某些属性和方法在引用接口时可见,但在任何派生类中不可见。因此,只有在用作IProgress<T>变量类型时才能“看到”它们,而在使用Progress<T>.

尝试这个:

((IProgress<string>)progressPercentage).Report(i*100/numberOfIterations+1);
Run Code Online (Sandbox Code Playgroud)

或者当您只需要引用接口声明中可用的属性和方法时:

IProgress<string> progressPercentage = ...;

progressPercentage.Report(i*100/numberOfIterations+1);
Run Code Online (Sandbox Code Playgroud)