Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async pass multiple parameters into ReportProgress method

How can I pass multiple parameters into the ReportProgress method? I was following this guide: MSDN to create a progressbar. My code looks like this.

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

As you may see, I was trying to add simply a new parameter (User pUser) to the ReportProgress method. Now I get an error inside the Button_Click method (line is marked).

Argument 1: cannot convert from method group into System.Action

best overloaded method match for 'System.Progress.Progress(System.Action)'-method has some invalid arguments

no overload for Report-Method takes 2 arguments

I was trying it like this, because in my real application I will have an ObersableCollection<User>. Is there maybe a better way I should go?

like image 383
MyNewName Avatar asked Mar 13 '17 08:03

MyNewName


2 Answers

You should pass a second parameter manually, because 'Progress' constructor takes only actions with one argument. Try this:

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

And remove second argument from 'pProgress.Report' method:

pProgress.Report(i); 
like image 135
Ivan Kishchenko Avatar answered Nov 18 '22 16:11

Ivan Kishchenko


I would prefer creating a message and pass multiple values to 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;
}
like image 21
Mukul Varshney Avatar answered Nov 18 '22 17:11

Mukul Varshney