Tuesday, December 10, 2013

Handling updates on a Form When Threads Are Involved

[code]
  Delegate Sub SetTextCallback(ByVal [text] As String)

    Private Sub ThreadProcSafe(ByVal vMessage As String, Optional ByVal vMessage2 As String = "")

        ' Check if this method is running on a different thread
        ' than the thread that created the control.
        If lstActions.InvokeRequired Then
            ' It's on a different thread, so use Invoke.
            Dim d As New SetTextCallback(AddressOf SetText)
            Me.Invoke(d, New Object() {Now.ToString() + "-" + vMessage + " " + vMessage2})
        Else
            ' It's on the same thread, no need for Invoke.
            lstActions.Items.Add(Now.ToString() + "-" + vMessage + " " + vMessage2)
        End If
    End Sub
    Private Sub SetText(ByVal vMessage As String)
        lstActions.Items.Add(vMessage)
    End Sub
[/code]
     There are issues when trying to update a form from a delegate or a different thread in a program. To access the form fields, you need to use something like the code above to make it "threadsafe" so that it will work.

My original program that uses this technique is the FolderWatcher project.

No comments:

Post a Comment