当BackgroundWorker发生异常时,在不同的线程上触发代码?
我有一个后台工作人员运行并寻找东西,当它找到东西时,我想更新我的主 WinForm。我遇到的问题是,当我尝试从后台工作人员更新 WinForm 时,我收到错误,告诉我无法修改在后台工作人员之外所做的内容(换句话说,我的表单中的所有内容) )。
有人可以提供一个简单的代码示例来说明如何让我的代码按照我想要的方式工作吗?谢谢!
I have a background worker that runs and looks for stuff, and when it finds stuff, I want to update my main WinForm. The issue that I'm having is that when I try to update my WinForm from my background worker, I get errors that tell me I can't modify things that were made outside of my background worker (in other words, everything in my form).
Can someone provide a simple code example of how I can get my code to work the way I want it to? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信您正在寻找 OnProgressChanged 事件。有关示例的更多信息:http://msdn。 microsoft.com/en-us/library/system.componentmodel.backgroundworker.onprogresschanged.aspx
I believe you're looking for the OnProgressChanged Event. More info with example here: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.onprogresschanged.aspx
如果我理解正确,您想要对表单本身进行更改,但是您不能从创建表单的线程以外的线程更改表单上的控件。为了解决这个问题,我使用 Form.Invoke() 方法,如下所示:
InvokeRequired 属性检查调用线程以确定它是否是对表单进行更改的正确线程,如果不是,则 Invoke 方法会将调用移动到表单的窗口上线。
If I understand correctly, you want to make a change on the form itself, however you cannot change a control on a form from a thread other than the thread the form was created on. To get around this I use the Form.Invoke() method like so:
The InvokeRequired property checks the calling thread to determine if it is the proper thread to make changes to the form, if no the Invoke method moves the call onto the form's window thread.