How to send more arguments to C # backgroundworker with modified event

I understand how we can pass one variable (progresspercentage) to the "progresschanged" function, for example.

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, for example:

 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.

+10
c # events backgroundworker
source share
3 answers

The ReportProgress method of the work component component is overloaded to pass the percentage and type value of the typed object:

 public void ReportProgress(int percentProgress, Object userState) 

In your usage requirement, you can combine the username and counter with the char delimiter and thus pass multiple values ​​inside the userState parameter; and break them inside the ProgressChanged () event when it is raised. You can also create a small class based on properties, fill it with values ​​and pass it using the parameter set by user userState.

For an example of using the ReportProgress overloaded method, see the following MSDN link:

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

+20
source share

If someone is looking for an exhaustive answer:

  1. A quick and easy approach would be object[] as in:

     worker.ReportProgress(i, new object[] { pc, username, score }); 
  2. A quick and type-safe approach would be System.Tuple<> as in:

     worker.ReportProgress(i, new System.Tuple<object, string, float>(pc, username, score)); 
  3. It would be best to write your own class (or perhaps inherit from System.Tuple<> ).

     public class PcUsernameScore { public object PC; public string UserName; public float Score; public PcUsernameScore(object pc, string username, float score) { PC = pc; Username = username; Score = score; } } 

    or

     public class PcUsernameScore : System.Tuple<object, string, float> { public PcUsernameScore(object p1, string p2, float p3) : base(p1, p2, p3) { } } 

    to have something like:

     worker.ReportProgress(i, new PcUsernameScore(pc, username, score)); 

- C # 7.1

  1. Inferred Tuple Feature:

    worker.ReportProgress(i, (pc: "pc", username: "me", score: 0));

+14
source share

Create a data transfer object with properties for the elements you want to transfer, and then pass them as a user state. In the OO world, the answer almost always is to create another object.

+7
source share

All Articles