从EventHandler调用Sub

时间:2010-06-07 19:47:53

标签: vb.net

我正在使用下面的代码来更新另一个线程的控件(效果很好)如何调用Sub(命名的UpdateList)? UpdateList使用所选SQL实例上的数据库列表更新列表视图,不需要参数。

Private Sub CompleteEventHandler(ByVal sender As Object, ByVal e As Microsoft.SqlServer.Management.Common.ServerMessageEventArgs)
    SetControlPropertyValue(Label8, "text", e.ToString)

    UpdateList()

    MessageBox.Show("Restore Complete")
End Sub

Delegate Sub SetControlValueCallback(ByVal oControl As Control, ByVal propName As String, ByVal propValue As Object)

Private Sub SetControlPropertyValue(ByVal oControl As Control, ByVal propName As String, ByVal propValue As Object)
    If (oControl.InvokeRequired) Then

        Dim d As New SetControlValueCallback(AddressOf SetControlPropertyValue)
        oControl.Invoke(d, New Object() {oControl, propName, propValue})
    Else
        Dim t As Type = oControl.[GetType]()
        Dim props As PropertyInfo() = t.GetProperties()
        For Each p As PropertyInfo In props
            If p.Name.ToUpper() = propName.ToUpper() Then
                p.SetValue(oControl, propValue, Nothing)
            End If
        Next

    End If

End Sub

基于: http://www.shabdar.org/cross-thread-operation-not-valid.html

1 个答案:

答案 0 :(得分:3)

从事件处理程序调用方法不是特殊情况 - 使用普通调用。

这里的问题是从后台线程到GUI线程的跨线程调用。为了克服它,您可以将以下代码放在UpdateList代码的开头:

If Me.InvokeRequired Then
    Me.Invoke(New Action(AddressOf UpdateList))
    Return
End If