完成后从 BackgroundWorker 函数获取回复

Get a reply from BackgroundWorker Function when complete

我试图从 Function BackgroundWorker 获得回复,但是它在 RunWorkerCompleted 触发之前命中 Return。一旦代码命中 'Thread_Load',它就会触发 Return.

在这里,我只是简单地返回一个字符串,但最终代码会发送一个 SQL 命令,对其进行处理并发回回复。

感谢您的帮助。

我试过使用 'While reply = Nothing' 但代码只是挂起。

主要形式

    Private Sub RibbonButton3_Click(sender As Object, e As EventArgs) Handles RibbonButton3.Click
        Dim NewCall As New TestThreads_SQL_Class
        Dim reply As String
        reply = NewCall.Thread_Load()
        MessageBox.Show(reply)
    End Sub

然后在TestThreads_SQL_Class

Imports System.ComponentModel




Public Class TestThreads_SQL_Class
    Public Class ArgumentType
        Public _a As Int32
        Public _b As Int32
    End Class

    Dim WithEvents BackgroundWorker1 As New BackgroundWorker
    Dim reply As String = Nothing


    Public Function Thread_Load()
        ' Create the argument object.
        Dim args As ArgumentType = New ArgumentType With {
            ._a = 5,
            ._b = 6
        }
        ' Start up the BackgroundWorker1. & Pass argument object to it.
        BackgroundWorker1.RunWorkerAsync(args)
        Return reply
    End Function


    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        ' Do some time-consuming work on this thread.
        System.Threading.Thread.Sleep(1000)
        ' Get argument.
        Dim args As ArgumentType = e.Argument
        ' Return value based on the argument.
        e.Result = args._a * args._b
    End Sub


    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        ' Called when the BackgroundWorker is completed.
        reply = (e.Result.ToString())
    End Sub

End Class

谢谢两位的回复。下面的效果很好。

    While Me.BackgroundWorker1.IsBusy
        ' Keep UI messages moving, so the form remains 
        ' responsive during the asynchronous operation.
        Application.DoEvents()
    End While