如何在C#backgroundworker中发送更多参数改进了事件

use*_*493 10 c# events backgroundworker

我理解如何将一个变量(progresspercentage)传递给"progresschanged"函数,就像这样.

backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
Run Code Online (Sandbox Code Playgroud)

...

worker.ReportProgress(pc);
Run Code Online (Sandbox Code Playgroud)

...

private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
   this.progressBar1.Value = e.ProgressPercentage;
}
Run Code Online (Sandbox Code Playgroud)

但我想将更多变量传递给这个函数,有些事情如下:

worker.ReportProgress(pc,username,score);
Run Code Online (Sandbox Code Playgroud)

...

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
}
Run Code Online (Sandbox Code Playgroud)

抱歉,我是c#的新手,有人可以举个例子.

VS1*_*VS1 20

后台工作程序组件的ReportProgress方法被重载以传递百分比和对象类型状态值:

public void ReportProgress(int percentProgress, Object userState)
Run Code Online (Sandbox Code Playgroud)

在您的使用要求中,您可以使用char分隔符连接UserName和Score,因此在userState参数内传递多个值; 并在引发它时将它们拆分在ProgressChanged()事件中.您还可以创建基于小属性的类 - 使用值填充它并使用userState对象类型参数传递.

有关如何使用重载的ReportProgress方法的示例示例,请查看以下MSDN链接:

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


Biz*_*han 14

如果有人正在寻找一个全面的答案:

  1. 快速简单的方法将object[]如下:

    worker.ReportProgress(i, new object[] { pc, username, score });
    
    Run Code Online (Sandbox Code Playgroud)
  2. 快速和类型安全的方法将System.Tuple<>如下:

    worker.ReportProgress(i, new System.Tuple<object, string, float>(pc, username, score));
    
    Run Code Online (Sandbox Code Playgroud)
  3. 最佳做法是编写自定义类(或者可以从中继承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;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    要么

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

    有类似的东西:

    worker.ReportProgress(i, new PcUsernameScore(pc, username, score));
    
    Run Code Online (Sandbox Code Playgroud)

  • 您也可以传递自定义类或结构而不是元组 (2认同)

Way*_*ner 7

创建一个数据传输对象,其中包含要传递的项的属性,然后将其作为用户状态传递.在OO世界中,答案几乎总是创造另一个对象.