gpt4 book ai didi

VB.NET WinForms - 如何从BackgroundWorker的线程访问主线程的对象?

转载 作者:行者123 更新时间:2023-12-02 03:23:06 24 4
gpt4 key购买 nike

我正在使用BackgroundWorker,我希望BackgroundWorker从数据库中检索数据,同时用户仍然可以在表单上执行其他任务。问题是,检索数据后,我似乎无法从 BackgroundWorkerDoWork 事件访问我的 Form 中的 ListView,我将使用我检索到的数据填充该 ListView。我应该怎么办?我错过了什么吗?

考虑这个例子,这就是我的做法:

Public Class Test
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Label1.Text = "Hello World"
End Sub
End Class

最佳答案

BackgroundWorker 的文档非常清楚:

You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.

<小时/>

样本"How to: Download a File in the Background"显示了在主线程和后台工作程序之间共享对象的一种示例方式 - 通过安排将此类对象存储在类级别的变量中。

关于VB.NET WinForms - 如何从BackgroundWorker的线程访问主线程的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6937300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com