Threading: How to update label or close form

馋奶兔 提交于 2020-01-16 18:45:47

问题


I haven't really done much with threads before and I'm having a problem updating a label and closing a form.

When debugging, the CloseDialog() sub is definitely running in the main thread so I don't understand why it's not closing. There are no loops or anything else running on the form to keep it open. I'm also having a problem updating the text on a label with information passed from another thread in real time.

The AddOUToTreeView sub gets invoked and works fine, but the subs from frmStatus never do anything.

frmMain:

Private WithEvents bkg As New ADSearcher

Private Sub startSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles startSearch.Click

    With bkg
        .RootPath = "LDAP://domain.com"
        .FilterString = "(objectCategory=organizationalUnit)"
        If Not integratedAuth Then
            .UserID = "user"
            .Password = "pass"
        End If
        .PageSize = 5
        .PropertiesToLoad = New String() {"cn", "name", "distinguishedName", "objectCategory"}

        Dim search As New Threading.Thread(AddressOf .StartSearch)
        search.Start()

        Dim statusDialog As frmStatus = New frmStatus
        statusDialog.Show() 'I want to use ShowDialog() but removed it when trouble shooting

    End With
End Sub

Private Delegate Sub displayStatus(ByVal entriesFound As Integer)
Private Sub bkg_ResultFound(ByVal ousFound As Integer) Handles bkg.ResultFound
    Dim display As New displayStatus(AddressOf frmStatus.UpdateOUSearcherStatus)
    Me.Invoke(display, New Object() {ousFound})
End Sub

Private Delegate Sub displayResult(ByVal node As TreeNode)
Private Delegate Sub closeStatusDialog()
Private Sub bkg_SearchCompleted(ByVal ouNodes As TreeNode) Handles bkg.SearchCompleted
    Dim display As New displayResult(AddressOf AddOUToTreeView)
    Me.Invoke(display, New Object() {ouNodes})

    Dim closeStatus As New closeStatusDialog(AddressOf frmStatus.CloseDialog)
    Me.Invoke(closeStatus)

End Sub

Private Sub AddOUToTreeView(ByVal node As TreeNode)
    tvOU.Nodes.Add(node)
    tvOU.TopNode.Expand()
End Sub

frmStatus (Both of these functions do nothing):

Public Sub CloseDialog()
    'Me.DialogResult = Windows.Forms.DialogResult.OK
    Me.Close()
    'Me.Dispose()
End Sub

Public Sub UpdateOUSearcherStatus(ByVal entriesFound As Integer)
    'lblOUsFound.Text = Format("{0} Organizational Units Found", ousFound)
    lblOUsFound.Text = entriesFound.ToString
End Sub

In my ADSearcher class I have:

Public Event ResultFound(ByVal ousFound As Integer)
Public Event SearchCompleted(ByVal ouNodes As TreeNode)

and raise the events with:

RaiseEvent ResultFound(resultCount)
'and
RaiseEvent SearchCompleted(rootNode)

来源:https://stackoverflow.com/questions/25836131/threading-how-to-update-label-or-close-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!