进度<>没有报告功能

本文关键字:报告 功能 进度 | 更新日期: 2023-09-27 18:34:30

我有Windows表单应用程序,这是我的代码:

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

我收到编译错误,指出"System.Progress"不包含"报告"的定义,并且找不到接受类型为"System.Progress"的第一个参数的扩展方法"报告"(您是否缺少使用指令或程序集引用?

如果你看一下进度类:

public class Progress<T> : IProgress<T>

并且接口IProgress具有功能报告:

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

我错过了什么?

进度<>没有报告功能

Progress<T>使用显式接口实现实现了该方法。因此,您无法访问具有类型为 Progress<T> 的实例的 Report 方法。您需要将其转换为IProgress<T>才能使用Report

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

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

或使用石膏

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

我更喜欢前一个版本,后者很尴尬。

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

显式接口实现用于使某些属性和方法在引用接口时可见,但不在任何派生类中可见。因此,您仅在使用 IProgress<T> 作为变量类型时"看到"它们,但在使用 Progress<T> 时则不会。

试试这个:

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

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

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