后台工作者
如何与后台线程一起维护前台线程。如果我尝试将项目添加到 do work 中的列表中,则会出现跨线程异常。
how to maintain a foreground thread along with background thread. if i try to add items to the list in do work, it's giving me a cross thread exception.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,UI 更新只能从 UI 线程本身执行。
使用
BackgroundWorker
执行此操作的机制是调用工作线程的ReportProgress
方法(确保WorkerReportsProgress = true
)。此方法将引发ProgressChanged
事件,由 UI 线程处理。因此,如果您想将项目添加到
ListBox
控件,例如,基于BackgroundWorker
正在执行的某些工作,请调用ReportProgress
并传递任何内容您需要的数据作为参数。此数据将存储在UserState
ProgressChangedEventArgs
属性code> 由事件提供。您的事件处理程序可以获取此数据并用它填充
ListBox
。或者,您可以通过处理工作人员的 在末尾添加所有内容
RunWorkerCompleted
事件。如果您的工作人员执行的工作不需要那么长时间,那么这通常是更可取的,因为它更简单,并且对 UI 的压力较小(需要执行的离散更新较少)。In general, UI updates may only be performed from the UI thread itself.
The mechanism for doing this with a
BackgroundWorker
is to call the worker'sReportProgress
method (make sureWorkerReportsProgress = true
). This method will raise theProgressChanged
event, to be handled by the UI thread.So if you want to add items to a
ListBox
control, for example, based on some work yourBackgroundWorker
is doing, callReportProgress
and pass whatever data you need as a parameter. This data will be stored in theUserState
property of theProgressChangedEventArgs
supplied by the event. Your event handler can take this data and populate theListBox
with it.Alternately, you can add everything at the end by handling the worker's
RunWorkerCompleted
event. If the work performed by your worker does not take all that long, this is often preferable as it's simpler and it stresses the UI less (with fewer discrete updates to perform).如果要将项目添加到 DoWork-Event 的列表中,则需要“调用”控件。
查看此处了解更多详细信息。
If you want to add the item to the list in the DoWork-Event, you need to "invoke" the controls.
Look here for more details.
您可以使用 ListView 触发事件来执行将项目添加到列表的工作,如下面的示例所示。
You can fire event that do the work of adding items to the list as shown in the below example using ListView.