datatheoz

VB.Net Thread Sample

Sep 24th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 0.95 KB | None | 0 0
  1. 'under Public Class Form1
  2. Private Shared KeepRunning As Boolean
  3.  
  4. 'Settings
  5. Private Shared Threads As Integer = 9
  6. Private Shared ClosedThreads As Integer = 0
  7.  
  8. 'under Start button
  9. KeepRunning = True
  10.  
  11. For i As Integer = 0 to Threads
  12.     Dim t As New Thread(AddressOf StartThread) With {.IsBackground = True}
  13.     t.Start
  14. Next
  15.  
  16. 'add this sub
  17. Private Sub StartThread
  18.     Dim loops As Integer
  19.  
  20.     While KeepRunning
  21.         loops += 1
  22.         Debug.Print($"Running some function in thread ID: {Thread.CurrentThread.ManagedThreadId}, loops: {loops}")
  23.         Thread.Sleep(10000)'Pause this thread for 10 secs.
  24.     End While
  25.  
  26.     Debug.Print($"Leaving thread (ID={Thread.CurrentThread.ManagedThreadId}), loops: {loops}")
  27.  
  28.     If Interlocked.Increment(ClosedThreads) > Threads
  29.         ClosedThreads = 0
  30.         Debug.Print("All threads have exited.")
  31.     End If
  32. End Sub
  33.  
  34. 'under Stop button
  35. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  36.     KeepRunning = False
  37. End Sub
Add Comment
Please, Sign In to add comment