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

发布于 2024-11-27 23:46:09 字数 698 浏览 1 评论 0原文

我正在使用 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

I'm working with BackgroundWorker, I want the BackgroundWorker do the retrieval process of data from database while the user can still do another task on the form. The problem is, after retrieving the data, I can't seem to access the ListView in my Form from the DoWork event of BackgroundWorker, I will populate that ListView using the data I've retrieved. What should I do? Am I missing something?

Consider this example, this is how I'm doing it:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长安忆 2024-12-04 23:46:09

BackgroundWorker 的文档非常清楚:

您必须小心,不要操作 DoWork 事件处理程序。相反,通过 ProgressChangedRunWorkerCompleted 事件。


示例“如何:在后台下载文件” 显示了一个可以在主线程和后台工作人员之间共享对象的示例方式 - 通过安排将此类对象存储在类级别的变量中。

The documentation for BackgroundWorker is quite clear:

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.


The sample "How to: Download a File in the Background" shows one example way that objects can be shared between the main thread and the background worker - by arranging for such objects to be stored in variables at the class level.

拧巴小姐 2024-12-04 23:46:09

DoWorkEventArgs 包含一个 Argument 属性,您可以在其中存储任何对象,例如包含用于操作 UI 的指令的用户定义的类。

DoWorkEventArgs contains an Argument property in which you can store any object, such as a user-defined class containing instructions for manipulating the UI.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文