BackgroundWorker返回值?

编程入门 行业动态 更新时间:2024-10-28 07:27:29
本文介绍了BackgroundWorker返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下代码将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返回值?

本文发布于:2023-10-26 14:43:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530448.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   BackgroundWorker

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!