Mr *_*ubs 0 vb.net multithreading thread-safety synclock
我有一个类,其中有两个方法,一个调用一个创建并执行多个线程的类,另一个是一个事件处理程序,它处理在这些线程完成时引发的事件(然后再次调用第一个方法).
我知道处理事件的方法在引发事件的线程中运行.因此,我SyncLock一个成员变量,说明正在运行多少个线程并从中减去一个:
SyncLock Me ' GetType(me)
_availableThreads -= 1
End SyncLock
Run Code Online (Sandbox Code Playgroud)
所以我有几个问题:
主要问题:我是否应该在类中的任何地方使用SyncLock'ing _availableThreads - 即在创建线程的方法中(在创建线程时添加1)
与此问题相关的附带问题:
我通常会同步SyncLock当前的实例,但我已经看到了SyncLocks类型的代码,那么同步锁定SyncLock(Current Instance)和_availableThreads?之间的区别是什么?
这两者之间会有性能差异吗?并且有什么小的我可以锁定以上不影响其他任何东西 - 可能是一个单独的'挂锁'对象创建的唯一目的是锁定类中的东西?
注意:_available线程的唯一目的是控制在任何给定时间可以运行的线程数,并且线程处理可能需要数小时才能运行的作业.
码:
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
Run Code Online (Sandbox Code Playgroud)
你不应该SyncLock是实例或类型.你总是想要SyncLock一个完全在类控制范围内的变量,而这些变量都不是.你应该声明一个私人New Object并使用它为你的SyncLock.
Private lockObject as New Object()
Run Code Online (Sandbox Code Playgroud)
...
SyncLock lockObject
...
End SyncLock
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6704 次 |
| 最近记录: |