当我开始BackgroundWorker
时,我可以传递任意参数:
backgroundWorker1.RunWorkerAsync(someStuff);
预期用途是将此任意参数提供给DoWork
方法:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Object someStuff = e.Argument;
...
}
现在我想在完成回调期间回复相同的论点:
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
Object myStuff = e.Argument;
...
}
不是 e.Argument
。
是UserState
:
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
Object myStuff = e.UserState;
...
}
但这是一个已知的错误,UserState
永远不会被设置或设置为任何东西。
那么什么是好的解决方法?
答案 0 :(得分:2)
将对象数组中的参数与实际结果一起返回。来自doWork处理程序。
BackgroundWorker bgw = null;
void main()
{
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
string otherResult = "Some Work Done";
e.Result = new Object[2] {e.Argument, otherResult};
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//writes the argument;
Console.WriteLine(((object[])e.Result)[0]);
}