Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to BackgroundWorker that accepts more than one argument?

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?

like image 312
Jeff Meatball Yang Avatar asked Jul 17 '09 21:07

Jeff Meatball Yang


2 Answers

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);     }; 
like image 103
Ben M Avatar answered Sep 18 '22 00:09

Ben M


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); 
like image 44
Vijay Patel Avatar answered Sep 19 '22 00:09

Vijay Patel