从工作线程到委托更新UI

时间:2016-08-16 21:00:31

标签: vb.net multithreading delegates

由于某些原因,调用委托更新到UI并不适用于我的某个线程,但使用不同的委托以稍微不同的方式更新相同的控件确实有效。

这里有破碎的代码,我已经对那些被解释的行进行了评论

Private Sub RunBtn_Click(sender As Object, e As EventArgs) Handles RunBtn.Click
    Dim transferThread As New System.Threading.Thread(AddressOf RunTransfer)
    StartContinuousProg()
    UpdateStatus("Running Transfer...")
    StartTime = Date.Now

    incrementProgMethod = New incrementProgDelegate(AddressOf incrementProg)
    finishProgMethod = New finishProgDelegate(AddressOf finishProg)
    updateStatusMethod = New updateStatusDelegate(AddressOf UpdateStatus)
    writeErrorMethod = New writeErrorDelegate(AddressOf WriteError)
    writeWarningMethod = New writeWarningDelegate(AddressOf WriteWarning)
    writeAlertMethod = New writeAlertDelegate(AddressOf WriteAlert)
    EndTransferMethod = New EndTransferDelegate(AddressOf endTransfer)

    transferThread.Start()

End Sub

Private Sub RunTransfer()

    '(...Some work...)


    For catRow = 0 To CATImportArr.Length - 1
        Dim currentCATSerial, currentCATAsset As String
        currentCATSerial = LCase(CATImportArr(catRow).getSerialNumber)
        currentCATAsset = LCase(CATImportArr(catRow).getAssetNumber)

'This line produces this error: Unable to cast object of type 'System.String' to type 'System.Delegate'.
        Invoke(updateStatusMethod("Searching " & currentCATSerial & ", " & currentCATAsset & "..."))

'This line doesn't crash but the UI label doesn't change
        updateStatusMethod.Invoke("Searching " & currentCATSerial & ", " & currentCATAsset & "...")

'This line doesn't crash but the UI progress bar doesn't change
        Invoke(finishProgMethod)

这些是通过代理人调用的方法

Public Function UpdateStatus(ByRef text As String)
    ParentForm.StatusLbl.Text = text
    Return text
End Function

Public Sub finishProg()
    ParentForm.StatusProg.Value = 100
End Sub

1 个答案:

答案 0 :(得分:1)

Delegate只是一个包含对方法的引用的类。您无法将参数传递给Delegate本身。

要将参数传递给要调用的方法,在指定委托后,必须使用Control.Invoke(Delegate, Object())重载将参数传递给Invoke()方法:< / p>

Invoke(updateStatusMethod, "Searching " & currentCATSerial & ", " & currentCATAsset & "...")

由于Control.Invoke(Delegate, Object())的第二个参数被声明为ParamArray,您可以继续指定参数,如果需要,只需用逗号分隔它们:

Invoke(updateStatusMethod, [param1], [param2], [param3], ...)