代码之家  ›  专栏  ›  技术社区  ›  madlan

从事件处理程序调用Sub

  •  1
  • madlan  · 技术社区  · 14 年前

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

    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 回复  |  直到 14 年前
        1
  •  3
  •   Konrad Rudolph    14 年前

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

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

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