从后台线程访问主线程数据

时间:2017-06-06 14:25:45

标签: vb.net multithreading asynchronous

我正在使用后台工作程序来处理数据,而用户仍然可以自由地点击另一个中止进程的按钮。 但是,backgroundworker中的代码需要几个数据,例如它需要知道是否选中了单选按钮。

有没有办法从后台线程访问另一个线程中的数据?或者我应该创建保存此信息的全局变量吗?

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

    Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        If RadioButton1.IsChecked Then
           MsgBox("It works")
        End If
    End Sub
End Class

1 个答案:

答案 0 :(得分:2)

您可以将RadioButton检查状态传递给RunWorkerAsync方法,如下所示:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    BackgroundWorker1.RunWorkerAsync(RadioButton1.Checked)
End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim checked As Boolean = CBool(e.Argument)
    If checked Then
        MessageBox.Show("It works")
    End If
End Sub

如果您需要从循环内部检查RadioButton 连续,请告诉我,因为这会有所不同。