完成后从后台工作线程函数获取回复



我试图从函数后台工作线程获取回复,但它在 RunWorkerCompleted 触发之前命中返回。一旦代码命中"Thread_Load",它就会触发 Return。

在这里,我只是取回一个字符串,但结束代码会发送一个 SQL 命令,处理它并发回回复。

感谢您的帮助。

我尝试使用"虽然回复=什么都没有",但代码只是挂起。

在主窗体中

    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

最新更新