vb.net - Windows服务: How to trigger OnStop when the worker thread stops

标签 vb.net multithreading service

我在VB.NET中创建了Windows服务。 OnStart创建一个工作线程并返回。辅助线程可以正常启动,并尝试连接到数据库。如果建立连接,线程将进入无限循环,这是预期的行为。

Dim _shutdown As Boolean = False 
Private _oPollingThread As Thread

Protected Overrides Sub OnStart(ByVal args() As String)
    _oPollingThread = New Thread(New System.Threading.ThreadStart(AddressOf PollProcess))
    _oPollingThread.Start()
End Sub

如果服务是手动关闭的(由Windows用户进入“服务”并单击“停止”),则OnStop会设置一个 bool 值;否则,将设置为boolean。工作线程看到此消息并成功关闭自身,OnStop加入,服务停止。都好。
Protected Overrides Sub OnStop()
    _shutdown = True

    ' Allow poll process to shut down gracefully (give it up to ten seconds...)
    Dim shutdownCount As Integer = 0

    Do While _oPollingThread.Join(1000) = False And shutdownCount < 10
        shutdownCount = shutdownCount + 1
    Loop

    If _oPollingThread.IsAlive = True Then
        _oPollingThread.Abort()
    End If

End Sub

问题是,如果工作线程未连接到数据库,如何使服务停止?一旦工作线程终止(而不是进入其无限循环),Windows服务将保持 Activity 状态,并且OnStop不会运行。

最佳答案

嗯,尽管我不确定您是否需要BackgroundWorker,但我认为Tony Hinkle可能在事件上走了正确的路。您可以声明一个由工作线程引发的WorkerStopped事件吗?然后,该服务可以具有处理它的Sub并停止该服务。

看起来像这样:

Public Class WinService
    '...OnStart(), OnStop()...

    Dim _shutdown As Boolean = False
    Private _oPollingThread As Thread
    Private Event WorkerStopped(sender As Object, e As EventArgs)

    Private Sub PollProcess()
        '...Attempt to connect to db...

        'See if attempt was successful, raise event if not.
        If databaseConnectionFailed Then
            RaiseEvent WorkerStopped(Me, Nothing) 'Could pass back data (error msg?) in EventArgs if desired
        Else
            'Connected to db successfully; proceed
            '...
        End If
    End Sub

    Private Sub StopWork(sender As Object, e As EventArgs) Handles Me.WorkerStopped
        Me.Stop()
    End Sub
End Class

如果想花哨的话,可以声明自己的自定义WorkerStoppedEventArgs类型,然后传递该类型,而不是普通的EventArgs。或者在自定义的地方,您可以不带任何参数,但是我想在那儿遵循惯例。

我希望我能保证这项工作会成功,但是距我编写Windows Service已有6年了,而且我还记得,启动并尝试使用它们并非易事!

关于vb.net - Windows服务: How to trigger OnStop when the worker thread stops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30381028/

相关文章:

vb.net - 多个 if 语句检查字符串长度并缩短

Access 中旧 VB.NET 项目中的 MYSQL 连接字符串

c# - 我需要调用 TcpListener.Stop() 吗?

c# - 多线程应用程序中的异常。

java - Android 10 java 中销毁应用程序后后台服务在 20 秒后停止

vb.net - Windows 脚本宿主对象模型的 Interop.IWshRuntimeLibrary.dll 引用与可执行文件相同的目录

c# - .NET 线程 : How to wait for other thread to finish some task

azure - Azure 上的调度程序

android - bindService 在单击按钮时不起作用,但在 onCreate 中起作用 - android

vb.net - 在 VB.NET 中搜索/替换