我有一个类,其中有两个方法,一个调用一个创建并执行多个线程的类,另一个是一个事件处理程序,用于处理这些线程完成时引发的事件(然后再次调用第一个方法)。
我了解处理事件的方法在引发事件的线程中运行。因此,我SyncLock
是一个成员变量,表示有多少线程正在运行并从中减去一个:
SyncLock Me ' GetType(me)
_availableThreads -= 1
End SyncLock
所以我有几个问题:
主要问题:我是否应该_availableThreads
在类中的任何地方都同步锁定 - 即在创建线程的方法中(创建线程时加 1)
与此问题相关的附带问题:
我通常
SyncLock
是当前实例,但我已经看到了该类型的代码,那么同步锁定(当前实例)和SyncLock
之间有什么区别?Me
GetType(Me)
两者之间会有性能差异吗?有没有什么更小的我可以锁定上面不影响其他任何东西的东西——也许是一个单独的“挂锁”对象,其唯一目的是在一个类中锁定东西?
注意: 的唯一目的_availableThreads
是控制在任何给定时间可以运行多少线程以及线程处理可能需要数小时才能运行的作业。
代码:
Public Class QManager
Private _maxThreadCount, _availableThreads As Integer
Public Sub New(ByVal maxThreadCount As Integer)
Me.MaximumThreadCount = maxThreadCount
End Sub
Public Sub WorkThroughQueue()
//get jobs from queue (priorities change, so call this every time)
Dim jobQ As Queue(Of QdJobInfo) = QueueDAO.GetJobList
//loop job queue while there are jobs and we have threads available
While jobQ.Count > 0 And _availableThreads <= _maxThreadCount
//create threads for each queued job
Dim queuedJob As New QdJob(jobQ.Dequeue)
AddHandler queuedJob.ThreadComplete, AddressOf QueuedJob_ThreadCompleted
_availableThreads += 1 //use a thread up (do we need a sync lock here?)***************************
queuedJob.Process() //go process the job
End While
//when we get here, don't do anything else - when a job completes it will call this method again
End Sub
Private Sub QueuedJob_ThreadCompleted(ByVal sender As QdJobInfo, ByVal args As EventArgs)
SyncLock Me //GetType(me)
_availableThreads -= 1
End SyncLock
//regardless of how the job ended, we want to carry on going through the rest of the jobs
WorkThroughQueue()
End Sub
#Region "Properties"
Public Property MaximumThreadCount() As Integer
Get
Return _maxThreadCount
End Get
Set(ByVal value As Integer)
If value > Environment.ProcessorCount * 2 Then
_maxThreadCount = value
Else
value = Environment.ProcessorCount
End If
LogFacade.LogInfo(_logger, "Maximum Thread Count set to " & _maxThreadCount)
End Set
End Property
#End Region
End Class