以下代码将1到100之间的数字相加并返回总和.我想做的是在后台工作程序中运行计算并返回一个值.问题是在DoWork完成之前返回returnValue.在返回值之前,我如何等待后台工作人员完成? (我似乎无法将退货放入我的DoWork中...)
The following code adds the numbers from 1 to 100 and returns the sum. What I'm trying to do is run the calculations in a backgroundworker and return a value. The problem with this is that returnValue is returned before DoWork completes. How can I have it wait for my background worker to complete before returning a value? (I can't seem to put the return in my DoWork...)
double returnValue = 0; var b = new BackgroundWorker(); b.DoWork += new DoWorkEventHandler( delegate(object sender, DoWorkEventArgs e) { for(int i=0;i<100;i++){ returnValue += (i+1); } } ); b.RunWorkerAsync(); return returnValue;附录:在同一线程上发送消息泵而不是在后台工作程序上运行消息泵会更好吗?
此外,这只是示例代码,我的实际代码需要一分钟多的时间才能完成.
Also, this is just example code, my actual code takes more than a minute to complete.
推荐答案订阅 RunWorkerCompleted 事件.该事件包含后台操作的返回值.
Subscribe to the RunWorkerCompleted event. That event contains the return value of the background operation.
当然,该值将从DoWorkEventHandler内部返回,就像这样:
Of course, that value would be returned from inside the DoWorkEventHandler, like so:
b.DoWork += new DoWorkEventHandler( delegate(object sender, DoWorkEventArgs e) { double returnValue = 0; for(int i=0;i<100;i++){ returnValue += (i+1); } return returnValue; } );更多推荐
BackgroundWorker返回值?
发布评论