后台工作人员返回值?
以下代码将 1 到 100 之间的数字相加并返回总和。我想做的是在后台工作者中运行计算并返回一个值。这样做的问题是 returnValue 在 DoWork 完成之前返回。如何让它等待后台工作人员完成后再返回值? (我似乎无法将回报放入我的 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;
附录:在同一线程上发送消息泵而不是在后台工作程序上运行它会更好吗?
另外,这只是示例代码,我的实际代码需要一分多钟才能完成。
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;
Addendum: Would it be better to send a message pump on the same thread instead of running this on a background worker?
Also, this is just example code, my actual code takes more than a minute to complete.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
订阅
RunWorkerCompleted
< /a> 事件。该事件包含后台操作的返回值。当然,该值将从 DoWorkEventHandler 内部返回,如下所示:
Subscribe to the
RunWorkerCompleted
event. That event contains the return value of the background operation.Of course, that value would be returned from inside the
DoWorkEventHandler
, like so:我在这里并没有真正看到问题,但我认为您正在寻找的是名为
RunWorkerCompleted
的事件。当DoWork
委托完成时会引发该异常。如果这不是您想要的,我认为您需要重新表述您的问题。I don't really see a question here, but what I think you are looking for is the event called
RunWorkerCompleted
. That gets raised when theDoWork
delegate completes. If this is not what you are looking for, I think you need to rephrase your question.我发布了一个示例:此处
也许它可以帮助你:-)
这可能是异步启动的效果。您可以告诉后台工作人员何时开始或直接说开始。如果你没有明确地说他应该现在就开始,那么他会在 c# 认为现在是开始的好时机时开始:-)
i have postet a sample: here
maybe it can help you :-)
this can be the effect of the async start. you can tell the backgroundworker when to start or just say start. if you don´t explicit say that he should start NOW he starts when c# thinks it is a good time to start :-)
如果像我一样,您无法使用接受的答案,因为 DoWorkEventHandler 返回 void,下面的代码可能会有所帮助。
If, like me, you were not able to use the accepted answer because DoWorkEventHandler returns void, the code below might help.
您正在尝试与BackgroundWorker 进行同步操作,这是坏。但如果必须的话,您可以使用 IsBusy 标志。
You are trying to do a synchronous operation with BackgroundWorker which it BAD. But if you must, you could use the IsBusy flag.