Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to ensure instances of class finish before main terminates?
    text
    copied!<p>I have a MultiThreading issue and conceptual question using Visual Basic (but it applies to almost all languages). I have a function which:</p> <ol> <li>creates 5 instances of a class which each spawns a thread which calls a function</li> <li>The Function sleeps for X milli-seconds</li> <li>prints to console</li> <li>then terminates the thread</li> </ol> <p><strong>How can I ensure all instances of the class gets a chance to finish before main cuts it off??</strong></p> <p>Most relevant help through research: <a href="https://stackoverflow.com/questions/2436142/how-do-i-pause-main-until-all-other-threads-have-died">How do I pause main() until all other threads have died?</a></p> <p>Here is my code: </p> <pre><code>Imports System Imports System.Threading Imports System.Collections.Generic Module Module1 Private raceTrack As New List(Of RaceCar) Sub Main() CreateRace() 'Main() would quit when the 5 car objects are created =[ 'How do I make sure Main will not exit until all racecars are done? End Sub Sub CreateRace() For index As Integer = 1 to 5 raceTrack.Add(new RaceCar(index)) Next End Sub Public Class RaceCar Private testThread as Thread = New Thread(AddressOf StartEngine) Private carId as Integer Public Sub New(ByVal carNumber as Integer) me.carId = carNumber Me.TestThread.Start() Me.TestThread.Join() End Sub Public Sub StartEngine() Console.WriteLine(String.Format("Car#{0} is going!", Me.carId)) Thread.Sleep(100*Me.carId) Console.WriteLine(String.Format("Car#{0} is DONE!", Me.carId)) End Sub End Class End Module </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload