multithreading not working?

rbreidenstein

Member
Joined
Dec 4, 2005
Messages
21
Programming Experience
1-3
I am attempting to learn how to multithread and i am making this as a simple sample.

but it doesn't work, the threads run one after the other instead of thread2 completing before thread1.

any suggestions?

VB.NET:
Imports System.Threading
Public Class Form1
    Public Delegate Sub StepProgressBar()

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim Thread1 As System.Threading.Thread
        Dim Thread2 As System.Threading.Thread
        ProgressBar1.Value = 0
        ProgressBar2.Value = 0
        ProgressBar1.Maximum = 9999
        ProgressBar2.Maximum = 999

        ProgressBar1.Step = 1
        ProgressBar2.Step = 1

        Thread1 = New System.Threading.Thread(AddressOf Run1)
        Thread2 = New System.Threading.Thread(AddressOf Run2)

        Thread1.Start()
        Thread2.Start()
    End Sub
    Sub stepBar2()
        Dim _step2counter As Integer = 0

        _step2counter = 0
        Do While _step2counter <= ProgressBar2.Maximum

            ProgressBar2.PerformStep()
            _step2counter += 1

        Loop
    End Sub
    Sub stepBar1()
        Dim _step1Counter As Integer = 0

        Do While _step1Counter <= ProgressBar1.Maximum

            ProgressBar1.PerformStep()

            _step1Counter += 1
            Thread.Sleep(0)
        Loop
    End Sub

    Sub Run1()
        ProgressBar1.Invoke(New StepProgressBar(AddressOf stepBar1))
        ' ProgressBar1.Invoke(New StepProgressBar(AddressOf stepBar), New _
        '  Object() {1})
        'Me.ProgressBar1.PerformStep()
    End Sub

    Sub Run2()
        ProgressBar2.Invoke(New StepProgressBar(AddressOf stepBar2))
        ' ProgressBar2.Invoke(New StepProgressBar(AddressOf stepBar), New _
        'Object() {1})
        ' Me.ProgressBar2.PerformStep()
    End Sub
End Class
 
Last edited by a moderator:
You're telling Thread1 to sleep for zero time so it won't sleep at all. Also, what's the point of the _step1counter and _step2Counter variables? Surely you should be testing the Value property of the ProgressBars against their Maximums.
 
i got it to work, in the code i was actually telling a thread to sleep but not the acutally thread i wanted. thread.sleep(0) means to pass any remaining time to the next thread.
 
Back
Top