开发者

is this a reasonable strategy for a thread in a Windows service

开发者 https://www.devze.com 2023-02-10 06:32 出处:网络
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.

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 possibil开发者_如何学Goities.

(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.


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 your OnStop, simply turn the timer off.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消