BackgroundWorker的替代方案,它接受多个参数?

时间:2009-07-17 21:29:13

标签: c# .net multithreading asynchronous backgroundworker

BackgroundWorker对象允许我们将单个参数传递给DoWorkEventHandler。

// setup/init:
BackgroundWorker endCallWorker = new BackgroundWorker();
endCallWorker.DoWork += new DoWorkEventHandler(EndCallWorker_DoWork);
...
endCallWorker.RunWorkerAsync(userName);

// the handler:
private void EndCallWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string userName = e.Argument as string;
    ...
}

要传递多个参数,我必须将它们包装在一个对象中,就像这个可怜的字符串数组一样:

// setup/init:

BackgroundWorker startCallWorker = new BackgroundWorker();
startCallWorker.DoWork += new DoWorkEventHandler(StartCallWorker_DoWork);
...
startCallWorker.RunWorkerAsync(new string[]{userName, targetNumber});


// the handler:
private void StartCallWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string[] args = e.Argument as string[];
    string userName = args[0];
    string targetNumber = args[1];
}

是否有另一个对象或模式允许我们很好地传递多个参数,或者理想情况下,编写我们自己的签名?

7 个答案:

答案 0 :(得分:45)

您可以使用闭包(Lambda):

backgroundWorker.DoWork += (s, e) => MyWorkMethod(userName, targetNumber);

或者使用delegate(匿名方法)语法:

backgroundWorker.DoWork += 
    delegate(object sender, DoWorkEventArgs e)
    {
        MyWorkMethod(userName, targetNumber);
    };

答案 1 :(得分:12)

使用打字对象有什么问题?

internal class UserArgs
{
    internal string UserName { get; set; }
    internal string TargetNumber { get; set; }
}

var args = new UserArgs() {UserName="Me", TargetNumber="123" };
startCallWorker.RunWorkerAsync(args);

答案 2 :(得分:4)

而不是类型化的对象。 C#4.0为我们提供了元组。我们可以使用一个元组来保存多个args。然后就不需要声明一个新类了。

答案 3 :(得分:3)

对象可以是列表或数组,也可以是一些。只需将对象设置为某种容器,然后在BackgroundWorker中进行转换。你需要确保你总是传递相同的类型。

答案 4 :(得分:2)

也许传递一个lambda函数作为你的对象?然后你在DoWork处理程序中调用它。

endCallWorker.RunWorkerAsync(new Action( () => DelegatedCallTarget(userName, targetNumber) ));

答案 5 :(得分:1)

创建一个包含所有参数的类

Class MyClass
{
     private string m_Username = string.Empty;
     private int m_Targetnumber;

     public MyClass(){}

     public string Username
     {
         get { return m_Username; }
         set { m_Username = value; }
     }

     public int TargetNumber
     {
         get { return m_TargetNumber; }
         set { m_TargetNumber = value; }
     }
 }



// setup/init:

BackgroundWorker startCallWorker = new BackgroundWorker();
startCallWorker.DoWork += new DoWorkEventHandler(StartCallWorker_DoWork);
...

MyClass thisClass = new MyClass();
thisClass.Username = "abcd";
thisClass.TargetNumber = 1234;
startCallWorker.RunWorkerAsync(thisClass);


// the handler:
private void StartCallWorker_DoWork(object sender, DoWorkEventArgs e)
{
     MyClass args = (MyClass)e.Argument;
     string userName = args.Username;
     string targetNumber = args.TargetNumber;
}

答案 6 :(得分:0)

为什么没有传递“one”对象是参数数组?您只需要从object参数将其强制转换回方法内的数组。