datatheoz icon

VB.Net Thread Sample

datatheoz | PRO | 09/25/18 12:32:07 AM UTC | 0 ⭐ | 275 👁️ | Never ⏰ | []
VB.NET |

950 B

|

None

|

0 👍

/

0 👎

'under Public Class Form1
Private Shared KeepRunning As Boolean
 
'Settings
Private Shared Threads As Integer = 9
Private Shared ClosedThreads As Integer = 0
 
'under Start button
KeepRunning = True
 
For i As Integer = 0 to Threads
    Dim t As New Thread(AddressOf StartThread) With {.IsBackground = True}
    t.Start
Next
 
'add this sub
Private Sub StartThread
    Dim loops As Integer 
 
    While KeepRunning
        loops += 1
        Debug.Print($"Running some function in thread ID: {Thread.CurrentThread.ManagedThreadId}, loops: {loops}")
        Thread.Sleep(10000)'Pause this thread for 10 secs.
    End While
 
    Debug.Print($"Leaving thread (ID={Thread.CurrentThread.ManagedThreadId}), loops: {loops}")
 
    If Interlocked.Increment(ClosedThreads) > Threads
        ClosedThreads = 0
        Debug.Print("All threads have exited.")
    End If
End Sub
 
'under Stop button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    KeepRunning = False
End Sub

Comments