异步将多个参数传递到ReportProgress方法

时间:2017-03-13 08:23:35

标签: c# wpf asynchronous

如何将多个参数传递到ReportProgress方法? 我按照本指南:MSDN创建了一个进度条。我的代码看起来像这样。

MainWindow.xaml

public User User { get; set; }

public MainWindow()
{
    InitializeComponent();
    this.User = new User();
    this.DataContext = User;
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var progressIndicator = new Progress<int>(ReportProgress); //here is the error
    await this.User.ReadUsers(progressIndicator, this.User)
}

void ReportProgress(int value, User pUser)
{
    this.User.Val = value;
}

User.xaml

public async Task<bool> ReadUsers(IProgress<int> pProgress, User pUser)
{
    for (int i = 1; i < 11; i++)
    {
        await Task.Delay(500);
        pProgress.Report(i, pUser);
    }

    return true;
}

正如您所看到的,我尝试向User pUser方法添加一个新参数(ReportProgress)。现在我在Button_Click方法中出现错误(标记了行)。

  

参数1:无法从方法组转换为System.Action

     

最佳重载方法匹配&#39; System.Progress.Progress(System.Action)&#39; -method有一些无效的参数

     

Report-Method没有重载需要2个参数

我是这样尝试的,因为在我的实际应用程序中,我会有一个ObersableCollection<User>。我可能有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

您应手动传递第二个参数,因为&#39;进展&#39;构造函数只接受带有一个参数的操作。试试这个:

new Progress<int>(i => ReportProgress(i, this.User));

并删除&#39; pProgress.Report&#39;中的第二个参数。方法:

pProgress.Report(i); 

答案 1 :(得分:1)

我更希望创建一条消息并将多个值传递给Report Progress

public class RMssg
{
    public int ProgressIndicator { get; set; }
    public User userInstance { get; set; }
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var progressIndicator = new Progress<RMssg>(r => ReportProgress(r));
    await this.User.ReadUsers(progressIndicator, this.User);
}

void ReportProgress(RMssg rMssg)
{
    this.User.Val = rMssg.ProgressIndicator;
    var user = rMssg.userInstance;
}



public async Task<bool> ReadUsers(IProgress<RMssg> pProgress, User pUser)
{
    for (int i = 1; i < 11; i++)
    {
        await Task.Delay(500);
        var rMssg = new RMssg() { ProgressIndicator = i, userInstance = pUser };
        pProgress.Report(rMssg);
    }

    return true;
}