I'm simulating some threading in a Windows Service, and the Thread.Start routine for each of my threads points directly to the following:
Private WithEvents CheckForOrdersTimer As System.Threading.Timer
Private Sub timerCheckForContracts_Tick(ByVal stateInfo As Object)
' Ticks every 5 seconds, then spawns threads until we're at our max
Do
If ThreadCollection.Count < MaxThreads Then
Dim t As New Threading.Thread(AddressOf SomeThreadingCode()
ThreadCollection.Add(t)
t.Start()
End If
Loop
End Sub
Private Sub SomeThreadingCode()
Do
Thread.Sleep(1000)
If Me.ThreadsShouldContinue = False Then ' Global thread-stopper
Exit Sub
End If
If (New Random).NextDouble > 0.8 Then ' On average, wait 5 seconds
Exit Do
End If
Loop
' Remove this thread from the main collection
ThreadCollection.Remove(Thread.CurrentThread)
End Sub
Pretty simple - the threads aren't even doing anything yet, but with more than two threads running at the same time, my processor (Core 2 Duo 2.4 w/ 4GB) gets pegged and Windows gets really sluggish. According to what I've read, Thread.Sleep shouldn't be consuming any resources at all while it waits, but it may as well be running in a tight timing loop.
Can anybody explain to me what's going on here?
EDIT: Per the requests, I've expanded the amount of code I'm using. I was initially doing some database work before spawning each thread, but I've removed it and the processor maximization still occurs with just the code here (and, of course, the OnStart method for the Windows Service.