线程处于休眠状态时,VB .Net服务不会停止

时间:2012-02-13 20:57:03

标签: .net vb.net multithreading sleep

我有一个VB .Net服务,它使用System.Threading而不是计时器来完成定时器应该做的事情。我的问题是在线程处于睡眠状态时停止服务。请参阅以下代码:

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分钟间隔时间并且线程唤醒。有没有办法捕获服务试图停止的信号,并中断线程?

3 个答案:

答案 0 :(得分:1)

在您当前的模型中,没有。您只使用一个线程,并且您的代码明确地“暂停”该线程15分钟,因此在此期间它对任何事件都没有响应。

但是,如果您对此采取略微改进的方法,则可以改进:在不同的线程中运行ServiceWorkerThread sub ,然后您的主线程可以保持响应外部事件。当“停止”信号到达时,您可以根据需要强行中止您的工作线程。

答案 1 :(得分:1)

这是我使用的代码。睡觉或表演时没有问题。

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

答案 2 :(得分:0)

查看Thread.Interrupt方法:http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx#Y0

但是,这要求您可以访问运行“服务”的Thread实例。如果这是主线程,那么它就是不行,但是如果它是你产生的线程,那么你可以调用中断,它将中断处于休眠/阻塞状态的Thread