VB.NET AddHandler正在创建表单的新实例。导致null委托

时间:2014-09-25 20:32:38

标签: vb.net multithreading events addhandler

此主题被标记为重复,因为我之前遇到过这个问题并且之前已经提出过问题。我现在通常知道如何解决它(即通过使用指向表单实例而不是其名称的变量)。但是这次是我需要引用的默认启动表单。所以没有变量存储它的实例,我不知道如何在没有它的情况下引用它的现有实例。

我有2个表单(frmMain和frmStatus)我创建了一个frmStatus实例并将其存储在frmMain上的statusDialog变量中。然后我创建一个新线程(对于我的ADSearcher类),它会触发事件,然后使用委托来调用statusDialog上的subs。 ADSearcher线程还创建了多个其他线程(对于我的ComputerSearcher线程),它还需要引发将使用委托调用statusDialog上的subs的事件。

问题在于ComputerSearcher线程。 AddHandler行似乎正在创建frmMain的新实例,这意味着statusDialog是Nothing / Null。为什么AddHandler会创建表单的新实例,有没有办法让它使用正确的实例?

我认为它创建一个新实例的原因是因为当我单步执行代码时它执行第一个AddHandler行,然后逐步执行frmMain顶部的变量声明(在任何subs之外),此时statusDialog变为Nothing

起点是Private Sub mnuSync_ADSync_Click(...)。这将创建第一个线程和类实例。我试图为你提供足够的代码,以便在不发表大量文章的情况下看到正在发生的事情。如果您需要任何其他代码,请询问。

提前致谢,

frmMain

Dim statusDialog As frmStatus 'Used to create an instance of the status dialog

Private Sub mnuSync_SyncAD_Click(sender As Object, e As EventArgs) Handles mnuSync_SyncAD.Click
    With adSync
        .RootPath = "LDAP://domain.com"
        .FilterString = "(objectCategory=organizationalUnit)"

        '### TO DO: Replace .UserID and .Password values with a stored value
        If Not integratedAuth Then
            .UserID = "...."
            .Password = "...."
        End If
        .PageSize = 5
        .PropertiesToLoad = New String() {"cn", "name", "distinguishedName", "dNSHostName", "objectCategory", "objectGUID"}

        'Create the status dialog
        statusDialog = New frmStatus

        ThreadPool.QueueUserWorkItem(AddressOf .StartSearch)

        statusDialog.ShowDialog()

    End With
End Sub

'[ADSearcher Events]
Private Delegate Sub displayOUStatus(ByVal ousFound As Integer)
Private Sub adSync_OUResultFound(ByVal ousFound As Integer) Handles adSync.OUResultFound
    Dim updateStatus As New displayOUStatus(AddressOf statusDialog.UpdateOUSearcherStatus)
    Me.Invoke(updateStatus, New Object() {ousFound})
End Sub

Private Delegate Sub displayResult(ByVal node As TreeNode)
Private Delegate Sub findMACAddresses(ByVal compCollection As ComputerCollection)
Private Sub adSync_SearchCompleted(ByVal ouNodes As TreeNode) Handles adSync.SearchCompleted
    Dim display As New displayResult(AddressOf AddOUToTreeView)
    Me.Invoke(display, New Object() {ouNodes})

    'Check for any computers which are no longer in Active Directory
    For Each compComparison As String In compGUIDComparison
        Dim query = From comp As Computer In computers Where comp.GUID = compComparison Select comp

        'If this computer is no longer in Active Directory remove it
        If query.Count > 0 Then
            computers.Remove(query(0))
        End If
    Next

    Dim macAddresses As New findMACAddresses(AddressOf GetMacAddresses)
    Me.Invoke(macAddresses, New Object() {computers})

End Sub
'[/ADSearcher Events]

'[ComputerSearcher Events]
Private Delegate Sub displayCompStatus(ByVal pcsFound As Integer)
Public Sub adSync_CompResultFound(ByVal pcsFound As Integer)
    Dim updateStatus As New displayCompStatus(AddressOf statusDialog.UpdateCompSearcherStatus)
    Me.Invoke(updateStatus, New Object() {pcsFound})
End Sub

Private Delegate Sub newComputer(ByVal computer As Computer)
Public Sub adSync_ComputerFound(ByVal name As String, ByVal fqdn As String, ByVal path As String, ByVal guid As String)
    Dim computer As New Computer
    computer.Name = name
    computer.FQDN = fqdn
    computer.Path = path
    computer.GUID = guid

    compGUIDComparison.Add(guid)

    Dim query = From comp As Computer In computers Where comp.GUID = computer.GUID Select comp

    If query.Count <= 0 Then 'If the computer hasn't already been discovered add it to the collection

        If Me.InvokeRequired Then
            Dim pc As New newComputer(AddressOf Me.computers.Add)
            Me.Invoke(pc, computer)
        Else
            computers.Add(computer)
        End If

    End If

End Sub
'[/ComputerSearcher Events]

ADSearcher Class

Sub New()
    SearchScope = DirectoryServices.SearchScope.OneLevel

    'Create reset events for the ComputerSearcher class threads
    For i As Integer = 0 To compSearchThreads.Count - 1
        compSearchThreads(i) = New ManualResetEvent(True)
    Next

End Sub

<MTAThread()>
Public Sub StartSearch()

#If Not Debug Then
    Try
#End If

    Dim rootEntry As New DirectoryEntry(RootPath)
    Dim rootNode As New TreeNode(rootEntry.Name)
    rootNode.Name = rootEntry.Path

    If Not IntegratedAuthentication Then
        rootEntry.Username = UserID
        rootEntry.Password = Password
    End If

    Dim searcher As New DirectorySearcher(rootEntry)
    searcher.PropertiesToLoad.AddRange(PropertiesToLoad)
    searcher.SearchScope = SearchScope
    searcher.PageSize = PageSize
    searcher.ServerTimeLimit = New TimeSpan(0, 10, 0)
    searcher.Filter = FilterString

    Dim queryResults As SearchResultCollection
    queryResults = searcher.FindAll()

    Dim result As SearchResult
    For Each result In queryResults

        Dim freeThread As Integer = WaitHandle.WaitAny(compSearchThreads)

        compSearchInstances(freeThread) = New ComputerSearcher(compSearchThreads(freeThread))

        With compSearchInstances(freeThread)
            .FilterString = "(objectCategory=computer)"
            If Not IntegratedAuthentication Then
                .UserID = UserID
                .Password = Password
            End If
            .PageSize = PageSize
            .SearchScope = SearchScope
            .PropertiesToLoad = PropertiesToLoad
        End With

        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf compSearchInstances(freeThread).FindComputers), result)

        Dim childNode As New TreeNode(CStr(result.Properties("name")(0)))
        childNode.Name = result.Path
        childNode.Tag = result.Properties("objectGUID")(0)
        rootNode.Nodes.Add(SearchSub(result, childNode))

        ouResultCount += 1
        RaiseEvent OUResultFound(ouResultCount)
    Next

    WaitHandle.WaitAll(compSearchThreads)
    RaiseEvent SearchCompleted(rootNode)
    ouResultCount = 0 'Reset the result count


#If Not Debug Then
    Catch Ex as Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical)
    End Try
#End If

ComputerSearcher Class

Sub New(ByVal doneEvent As ManualResetEvent)
    _doneEvent = doneEvent

    'Add Event Handler
    AddHandler Me.ComputerFound, AddressOf frmMain.adSync_ComputerFound
    AddHandler Me.IncrementCompResult, AddressOf frmMain.adSync_CompResultFound
End Sub

Public Sub FindComputers(ByVal parent As SearchResult)
#If Not Debug Then
    Try
#End If

    _doneEvent.Reset() 'Signal that the thread is working

    Dim subEntry As New DirectoryEntry(parent.Path)

    If Not IntegratedAuthentication Then
        subEntry.Username = UserID
        subEntry.Password = Password
    End If

    Dim searcher As New DirectorySearcher(subEntry)
    searcher.PropertiesToLoad.AddRange(PropertiesToLoad)
    searcher.SearchScope = SearchScope
    searcher.PageSize = PageSize
    searcher.ServerTimeLimit = New TimeSpan(0, 10, 0)
    searcher.Filter = FilterString

    Dim queryResults As SearchResultCollection
    queryResults = searcher.FindAll()

    Dim result As SearchResult
    For Each result In queryResults
        pcResultCount += 1

        Dim dNSHostName As String
        If result.Properties.Contains("dNSHostName") Then 'If the computer object has a value in dNSHostName (FQDN) store it else store the basic name
            dNSHostName = result.Properties("dNSHostName")(0)
        Else
            dNSHostName = result.Properties("name")(0)
        End If

        RaiseEvent ComputerFound(result.Properties("name")(0), dNSHostName, result.Path, result.Properties("objectGUID")(0).ToString)
        RaiseEvent IncrementCompResult(pcResultCount)

    Next

    _doneEvent.Set() 'Signal that the thread is finished

#If Not Debug Then
    Catch Ex as Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical)
    End Try
#End If

End Sub

1 个答案:

答案 0 :(得分:0)

替换以下两行:

AddHandler Me.ComputerFound, AddressOf frmMain.adSync_ComputerFound
AddHandler Me.IncrementCompResult, AddressOf frmMain.adSync_CompResultFound

使用:

AddHandler Me.ComputerFound, AddressOf My.Forms.frmMain.adSync_ComputerFound
AddHandler Me.IncrementCompResult, AddressOf My.Forms.frmMain.adSync_CompResultFound

这是另一个VB默认表单实例拍摄开发人员的例子。