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);
};