Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 938
user932493 Avatar asked Sep 07 '11 10:09

user932493


1 Answers

In case anyone is looking for a comprehensive answer:

  1. Fast & simple approach would be object[] as in:

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

     worker.ReportProgress(i, new System.Tuple<object, string, float>(pc, username, score));
    
  3. A better practice would be to write your custom class (or maybe 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 ValueTuple feature:

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

C# 9.0

  1. Best practice: To use record:

     public record PcUsernameScore(object PC, string UserName, float Score);
    
like image 182
Bizhan Avatar answered Sep 17 '22 19:09

Bizhan