How to send more arguments in C# backgroundworker progressed changed event

user932493 picture user932493 · Sep 7, 2011 · Viewed 22.3k times · Source

I understand how we can pass one variable(progresspercentage) to "progresschanged" function , like so.

backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);

...

worker.ReportProgress(pc);

...

private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
   this.progressBar1.Value = e.ProgressPercentage;
}

But I want to pass more variables to this function, some thing like:

worker.ReportProgress(pc,username,score);

...

private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
   this.progressBar1.Value = e.ProgressPercentage;
   this.currentUser.Value = e.UserName;  //as string
   this.score.Value = e.UserScore;  //as int
}

sorry I'm new to c#, could someone give me an example.

Answer

VSS picture VSS · Nov 7, 2011

The ReportProgress method of background worker component is overloaded to pass percentage and an object typed state value:

public void ReportProgress(int percentProgress, Object userState)

In your usage requirement you can concatenate the UserName and Score with a char separator, and so pass the multiple values inside the userState parameter; and split them inside the ProgressChanged() event when it is raised. You can also create a small property based class- fill it with values and pass using the userState object typed parameter.

For a sample example of how to use the overloaded ReportProgress method, please look at the below MSDN link:

http://msdn.microsoft.com/en-us/library/a3zbdb1t.aspx