【发布时间】:2010-03-03 00:48:30
【问题描述】:
我正在模拟 Windows 服务中的一些线程,我的每个线程的 Thread.Start 例程都直接指向以下内容:
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
非常简单 - 线程甚至还没有做任何事情,但是同时运行两个以上的线程,我的处理器(Core 2 Duo 2.4 w/4GB)被固定,Windows 变得非常缓慢。根据我所读到的,Thread.Sleep 在等待时根本不应该消耗任何资源,但它也可能在一个紧凑的时序循环中运行。
谁能给我解释一下这里发生了什么?
编辑:根据请求,我已经扩展了我正在使用的代码量。在生成每个线程之前,我最初是在做一些数据库工作,但我已经删除了它,并且仅使用此处的代码(当然还有 Windows 服务的 OnStart 方法)仍然会发生处理器最大化。
【问题讨论】:
-
线程代码看起来不错。这个函数调用了什么?
-
您是否在用力旋转产生其他两个的线程?
-
@Justin Ethier - 我已经更新了代码以包含生成代码。
-
@SB - 我不这么认为 - 我已经更新了代码。是否有工具可以用来查看每个线程上的资源使用情况,以便知道哪个线程在旋转?
标签: .net vb.net multithreading