我正在尝试创建一个使用BackgroundWorker
在Winforms程序中异步分配的方法。
void Assign<T>(Func<object> method, ref T obj)
{
var bw = new BackgroundWorker();
bw.DoWork +=
(object sender, DoWorkEventArgs e) =>
e.Result = ((Func<object>)(e.Argument))();
bw.RunWorkerCompleted +=
(object sender, RunWorkerCompletedEventArgs e) =>
obj = (T)e.Result; // Error here
bw.RunWorkerAsync(method);
}
Assign(slowMethodReturnsFloat, ref aFloatVariable);
Assign(slowMethodReturnsDataSet, ref aDataSetVar);
然而,我得到了错误:
“不能在lambda表达式中使用ref或out参数”
实现它的任何其他方式?任何不使用BackgroundWorker
的方法?
答案 0 :(得分:2)
考虑传递lambda而不是ref
作为第二个参数:
void Assign<T>(Func<object> method, Action<T> objSetter)
{
var bw = new BackgroundWorker();
bw.DoWork +=
(object sender, DoWorkEventArgs e) =>
e.Result = ((Func<object>)(e.Argument))();
bw.RunWorkerCompleted +=
(object sender, RunWorkerCompletedEventArgs e) =>
objSetter((T)e.Result);
bw.RunWorkerAsync(method);
}
Assign(slowMethodReturnsFloat, ret => aFloatVariable = ret);
Assign(slowMethodReturnsDataSet, ret => aDataSetVar = ret);
答案 1 :(得分:1)
我不确定T
是什么,但另一种选择可能是传递回调:
void Assign<T>(Func<object> method, Action<T> callBack);
void callBack(T result)