对于 Windows 服务中的线程来说,这是一个合理的策略吗?
在 OnStart 中,我将 HKLM 注册表值设置为“是”。
然后,我实例化 ac# 类,该类将其方法之一作为线程启动。
该方法处理来自远程服务的记录,然后休眠。
当它唤醒时,如果注册表项仍然为“是”,它将处理来自远程源的更多记录。
OnStop 将 HKLM 键设置为“否”并返回。
我不确定幕后发生了什么……似乎至少有两种可能性。
(A) 服务在 OnStop 退出后停止,但线程继续运行,直到它唤醒并退出。
(B) 服务等待线程结束然后退出。
我猜是(A),但我真的不知道。
不管怎样,这是一个合理的策略吗?谢谢/克。
In my OnStart, I set a HKLM registry value to "Yes".
I then instantiate a c# class which starts one of its methods as a thread.
The method processes records from a remote service then sleeps.
When it wakes, if the registry key is still "Yes" it processes more records from the remote source.
The OnStop sets the HKLM key to "No" and returns.
I'm not sure what happens behind the curtains ... it seems there are at least two possibilities.
(A) the service stops after the OnStop exits but the thread keeps running until after it wakes up and quits.
(B) the service waits for the thread to end and then exits too.
I'm guessing (A) but I really do not know.
Either way, is this a reasonable strategy? thnx / g.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我更喜欢使用
计时器
。在服务类中创建一个静态计时器变量,每次计时器到期时都会启动处理事件。在您的OnStop
中,只需关闭计时器即可。I prefer using a
Timer
. Make a static timer variable in your service class that kicks off your processing event each time the timer has elapsed. In yourOnStop
, simply turn the timer off.我不会使用注册表来做这样的事情。您想通知工作线程该退出了,并让它自行退出,但您可以比使用注册表做得更好。
使用布尔“keepRunning”变量而不是使用注册表。有一个“workInterval”设置/变量来指示应该多久完成一次工作,但将睡眠间隔设置得足够短,比如每隔几秒,以便足够频繁地唤醒并检查“keepRunning”变量,以便服务可以响应停止命令。如果“keepRunning”测试为假,只需退出主循环,您的服务进程就会结束。如果“keepRunning”为真,则测试是否到了工作时间,如果时间到则完成工作,然后再次睡眠。如果工作很长,请考虑经常从工作循环中检查“keepRunning”变量,以便在服务应该关闭时可以保存状态并正常退出。
您的 OnStop 处理程序将简单地将“keepRunning”设置为 false,而不执行任何其他操作。这样你就不需要用Thread.Abort之类的东西强行杀死worker,服务进程会在OnStop事件发生的几秒钟内关闭。
I would not use the registry for something like this. You want to notify the worker thread that it is time to exit, and let it exit on its own, but you can do better than using the registry.
Use a bool "keepRunning" variable instead of using the registry. Have a "workInterval" setting/variable that indicates how often work should be done, but set your sleep interval short enough, say every few seconds, to wake and check the "keepRunning" variable often enough that the service can be responsive to the stop command. If the "keepRunning" test is false, just exit the main loop and your service process will end. If "keepRunning" is true, then test to see if it is time to do work, do the work if it is time, then sleep again. If the work is lengthy, consider checking the "keepRunning" variable every so often from your work loop so you can save state and exit gracefully if the service is supposed to shut down.
Your OnStop handler will simply set "keepRunning" to false, and do nothing else. This way you don't need to forcibly kill the worker with something like Thread.Abort, and the service process will shut down within a few seconds of the OnStop event.