This page looks best with JavaScript enabled

VB.NET - Thread Safe Progress Bar

 ·   ·  ☕ 1 min read

Normally, when you are using .NET built-in progress bar in a multi-threaded application without Callback tricks, you are likely to get an exception on value assign, similar to the following:

thread exception

I recently wrote a fairly simple wrapper class, which solves the problem. See code below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Public Class MyProgressBar : Inherits ProgressBar

  Public Delegate Sub SetRefreshCallback()
  Public Delegate Sub SetValueCallback(ByVal v As Integer)

  Public Shadows Text As String = String.Empty

  Public Overloads Property Value() As Integer
    Get
      Return MyBase.Value
    End Get
    Set(ByVal value As Integer)
      If Me.InvokeRequired Then
        Me.Invoke(New SetValueCallback(AddressOf SetValue), New Object() {value})
      Else
        MyBase.Value = value
      End If
    End Set
  End Property

  Private Sub SetValue(ByVal v As Integer)
    MyBase.Value = v
  End Sub

End Class

Usage is simple: just assign the value like you normally do, in a thread worker sub. The difference of MyProgressBar is that you will not get a cross-thread exception.

Here’s a test project to play with. I put the original call there on purpose, to let you see the error.


Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)