gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:11:41 24 4
gpt4 key购买 nike

我在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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com