我有一个VB .Net服务,该服务使用System.Threading而不是计时器来基本上完成计时器应做的事情。我的问题是在线程处于 sleep 状态时停止服务。请参见下面的代码:
Imports System.Threading
Public Class AService
Private stopping As Boolean
Private stoppedEvent As ManualResetEvent
Public Sub New()
InitializeComponent()
Me.stopping = False
Me.stoppedEvent = New ManualResetEvent(False)
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
Me.stopping = True
Me.stoppedEvent.WaitOne()
End Sub
Private Sub ServiceWorkerThread(ByVal state As Object)
' Periodically check if the service is stopping.
Do While Not Me.stopping
' Perform main service function here...
' do anything here and wait 15 minutes before doing it again
Thread.Sleep(15 * 60000) ' Sleep for interval
Loop
' Signal the stopped event.
Me.stoppedEvent.Set()
End Sub
End Class
如果说在服务启动后1分钟,则无法停止该服务,直到它间隔15分钟并且线程唤醒为止。有什么方法可以捕获服务正在尝试停止并中断线程的信号?
最佳答案
这是我使用的代码。 sleep 或表演时停下来没有问题。
Class MyService
Inherits ServiceBase
Private Shared ReadOnly SleepPeriod As New TimeSpan(0, 15, 0)
Private Shared ReadOnly StopTimeout As New TimeSpan(0, 3, 0)
Private _TerminationHandle As New ManualResetEvent(False)
Private _IsRunning As Boolean = False
Private _ServiceThread As New Thread(Addressof ServiceMain)
Protected Overrides Sub OnStart(args As String())
_TerminationHandle.Reset()
_IsRunning = True
_ServiceThread.Start()
End Sub
Protected Overrides Sub OnStop()
_TerminationHandle.Set()
_IsRunning = False
' Terminate the thread if it doesn't stop within 3 minutes of request.
If Not _ServiceThread.Join(StopTimeout) Then _ServiceThread.Abort()
_TerminationHandle.Close() ' Can use .Dispose() if using .Net 4.0 or later.
End Sub
Private Sub ServiceMain()
Do
' TODO: Do work here. Watch for "_IsRunning = False" to abort working when stopping.
' Sleep for 15 minutes at a time. Terminate when service is stopping.
Loop While _IsRunning AndAlso TerminationHandle.WaitOne(SleepPeriod)
' TODO: Clean up.
End Sub
End Class
关于.net - 线程正在休眠时,VB .Net服务不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9267897/