Austin Davis
Austin Davis

Reputation: 3756

Trouble Marshalling the Ui Thread

I'm trying to update the text of a label from a seperate class on a separate thread. The other class raises an event which is handled here

    Private Sub handleChangeUI(ByVal sender As System.Object)
    Dim ytde As Data_Entry_Form.YTD = CType(sender, Data_Entry_Form.YTD)

    UpdateExcelLabel(ytde.LabelMessage)
End Sub

And in the updateExcelLabel method I was hoping to change the label's text with the following

 Private Delegate Sub updateExcelDelegate(txt As String)
Public Sub UpdateExcelLabel(text As String)
    If Me.lblExcel.InvokeRequired = True Then
        Dim del As New updateExcelDelegate(AddressOf UpdateExcelLabel)
        Me.lblExcel.BeginInvoke(del, text)
    Else
        Me.lblExcel.Visible = True
        Me.lblExcel.Text = text
        Me.lblExcel.Refresh()
    End If
End Sub

For some reason the Me.lblExcel.InvokeRequired is always returning true. I'm still very new when it comes to delegates and multi-threading so any help would be greatly appreciated.

Upvotes: 1

Views: 147

Answers (1)

prprcupofcoffee
prprcupofcoffee

Reputation: 2970

Per the documentation, BeginInvoke runs the delegate on the thread the control was created on, but it is asynchronous, so there is no guarantee the delegate has begun to run before the next time handleChangeUI is called.

I have always used Invoke in this situation, rather than BeginInvoke.

Upvotes: 4

Related Questions