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

标签 vb.net winforms multithreading backgroundworker

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

相关文章:

c# - 如何滚动到列表框的底部?

c# - 通过DataGridView向集合添加元素

linux - 多线程中的socket fd

c# - 其中一个线程阻止 .NET 程序完全停止。如何识别是哪一个?

c# - 这可以单独使用格式化字符串来完成吗?

VB.NET "For each"与 ".GetUpperBound(0)"

asp.net-mvc - 对于每个循环 LINQ 插入给我无法添加已存在的实体

VB.NET 4.0 : Looking to execute multiple threads, 但要等到所有线程都完成后再恢复

C# 从列表框拖放到 TreeView

Java 在文件被修改时获取通知