我有一個VB .Net服務,它使用System.Threading而不是定時器來基本上做一個定時器應該做的事情。我的問題是在線程處於睡眠狀態時停止服務。請參見下面的代碼:服務啓動VB .Net服務在線程休眠時不會停止
如果例如1分鐘後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
,就不能停止,直到它每隔15分鐘蜱和線程被喚醒。有什麼方法可以捕捉服務試圖停止的信號,並中斷線程?
由於其保護級別,_TerminationHandle.Dispose()不可訪問。有任何想法嗎?這是完美的解決方案 – 2012-02-14 15:55:37
我正在使用.Net 3.5,切換到4.0,現在它的工作。我必須做一些測試,但是謝謝,這是一個很好的代碼庫 – 2012-02-14 16:06:21
啊,我不知道這是最近的一次增加。你可以在早期版本的.Net中使用'.Close()'。我在答案中做了一個筆記。謝謝! – 2012-02-14 21:58:43