Alternative to BackgroundWorker that accepts more than one argument?

23,197

Solution 1

You could use a closure (Lambda):

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

Or with delegate (anonymous method) syntax:

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

Solution 2

What's wrong with using a typed object?

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

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

Solution 3

instead of a typed object. C# 4.0 provides us with tuple. We could use a tuple to hold multiple args. Then there is no need to declare a new class.

Solution 4

Object can be a list or array or some such. Just make your object a container of some sort, then cast within the BackgroundWorker. You need to make sure you're always passing in the same type though.

Solution 5

Maybe pass a lambda function as your object? Then you'd call it in the DoWork handler.

endCallWorker.RunWorkerAsync(new Action( () => DelegatedCallTarget(userName, targetNumber) ));
Share:
23,197
Jeff Meatball Yang
Author by

Jeff Meatball Yang

Taking some time to learn and share.

Updated on March 02, 2020

Comments

  • Jeff Meatball Yang
    Jeff Meatball Yang about 4 years

    The BackgroundWorker object allows us to pass a single argument into the 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;
        ...
    }
    

    To pass multiple arguments, I must wrap them in an object, like this poor string array:

    // 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];
    }
    

    Is there another object or pattern that allows us pass multiple arguments nicely, or ideally, write our own signature?