那么您认为防止C#Windows服务的多个线程同时运行的最佳方法是什么(该服务是否使用了timer该OnElapsed事件)?
使用lock()或mutex?
我似乎无法掌握这个概念mutex,但使用lock()似乎对我的情况很好.
我是否应该花时间学习如何使用mutex?
我正在开发一个有一些问题的Windows服务,Thread.Sleep()所以我想我会尝试使用计时器,因为这个问题建议:
事情是我不清楚如何实现这一点.我相信这是方法,但我只想确保:
'' Inside The Service Object
Dim closingGate As System.Threading.AutoResetEvent
Protected Overrides Sub OnStart(ByVal args() As String)
Dim worker As New Threading.Thread(AddressOf Work)
worker.Start()
End Sub
Protected Sub Work()
Dim Program = New MyProgram()
closingGate = New System.Threading.AutoResetEvent(False)
Program.RunService(closingGate)
End Sub
Protected Overrides Sub OnStop()
closingGate.Set()
End Sub
'' Inside My Programs Code:
Public Sub RunService(closingGate As AutoResetEvent)
Dim tmr As New Timer
'' ...and so on
closingGate.WaitOne()
End Sub
Run Code Online (Sandbox Code Playgroud)
除了使用VB.Net(开玩笑,但如果可以的话,我会使用C#.)我是否在正确的轨道上?这比使用更好Thread.Sleep()吗?