VB.Net Using Delegates for Form Updates from Worker Threads

by Tim on September 21, 2011

At Geekup Preston this week a conversation with @surlydev led to an explanation of how to use delegates to update a UI from a worker thread. Talk is cheap, and a code sample goes along way to help explain.

Imports System.Threading

Public Class DelegateDemo

    ' imagine a form with Button1 + Label1

    ' the thread
    Private _worker As Thread

    ' declare a kind of delegate with the signature you want
    Private Delegate Sub UpdateDelegate(ByVal s As String)

    ' declare an implmentation with matching signature
    Private Sub UpdateStatus(ByVal s As String)
        Me.Label1.Text = s
    End Sub

    ' kick-off the worker thread
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ' start a worker
        If _worker Is Nothing Then

            _worker = New Thread(AddressOf WorkerMain)
            _worker.Start()

        End If

    End Sub

    ' Worker thread
    Private Sub WorkerMain()

        Dim x As Integer = 0
        Do

            ' increment
            x += 1

            ' update UI + sleep
            ' this executes delegate + params on thread that owns the form
            Dim msg As String = String.Format("Hello {0}", x)
            Dim del As UpdateDelegate = AddressOf UpdateStatus
            Me.Invoke(del, msg)

            ' half a second snooze
            Thread.Sleep(500)

        Loop While x < 30

        ' thread's dead baby (will terminate when it exits this sub)
        _worker = Nothing

    End Sub

End Class

Leave your comment

Required.

Required. Not published.

If you have one.