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?
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); };
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With