Pass a ProgressBar ByRef to a custom class on a BackgroundWorker thread

jason2li

Member
Joined
Nov 18, 2005
Messages
22
Location
St. Louis, MO
Programming Experience
5-10
I'm trying to make a custom class that will use my main form's ProgressBar to show some progress. The function takes a LONG time, so I have to run it on a different thread (I'm using the BackgroundWorker).

How do I do this?

Here is a dummy application that essentially demonstrates what I'm trying to do (you'll have to add a ProgressBar to your form).

VB.NET:
Public Class Form1

    Private c As New TestClass
    Private WithEvents worker As New System.ComponentModel.BackgroundWorker

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        worker.RunWorkerAsync(ProgressBar1)

    End Sub

    Private Sub worker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles worker.DoWork

        Dim ProgressBar As ProgressBar = CType(e.Argument, ProgressBar)

        c.Generate(ProgressBar)

    End Sub

End Class

Public Class TestClass
    Inherits List(Of Integer)

    Public Sub Generate(ByRef ProgressBar As ProgressBar)

        ProgressBar.Minimum = 0
        ProgressBar.Maximum = 1000
        ProgressBar.Value = 0

        For i As Integer = 0 To 999

            MyBase.Add(i)
            ProgressBar.Value += 1

        Next
        ProgressBar.Value = 0

    End Sub

End Class

I've tried using my very limited knowledge of delegates, but I couldn't get it working.

I've found a workaround for now, which is raising events such as "Set_ProgressBar_Value" from inside my custom class, and then catching and handling the event from my main form and updating things accordingly... but I would think there is a better way to do this.
 
You can't do that because you are cross-threading. It is also bad design to have that "TestClass" class change the progressbar that doesn't belong to it, raising an event from the "TestClass" would be preferred, look at the sketch in post 4 here again.
 
Back
Top