Tech Blog‎ > ‎

VB.NET - Thread Safe Progress Bar

posted Mar 28, 2010, 2:33 PM by Victor Zakharov   [ updated Mar 15, 2014, 7:17 PM ]
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:


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

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.
ċ
ThreadSafeProgressBar.zip
(15k)
Victor Zakharov,
Mar 28, 2010, 3:01 PM
Comments