I've seen several posts on SO that are similar to my question, but none of them have solved my problem. I'm creating a windows service that is going to poll a Redis database every few seconds or so and perform an action based off of the result. I'd like to create a "thread pool" of sorts so that I can run multiple actions at the same time if I get a result from Redis while another command is being processed (on another thread).
One of my main problems is that when I stop my Windows service, the process still stays alive for ~30 seconds or so instead of closing down. Here are the relevant code snippets:
Thread Worker;
IDatabase db = ...;
AutoResetEvent StopRequest = new AutoResetEvent(false);
protected override void OnStart(string[] args) {
var poller = new Poller();
Worker = new Thread(() => poller.Poll(StopRequest));
Worker.Start();
}
protected override void OnStop() {
// Signal worker to stop and wait until it does
StopRequest.Set();
Worker.Join();
}
Here's an example of the Poller
classes Poll
method.
public async void Poll(AutoResetEvent finished)
{
var res = string.Empty;
while (!finished.WaitOne(1000))
{
res = db.StringGet($"task");
if (!String.IsNullOrEmpty(res))
{
ParseAction(res);
}
db.KeyDelete($"task");
}
}
So this code (with a lot trimmed out) stays running in the background correctly, and seems to process incoming queries from Redis just fine, but I'm having the issue with the process not closing correctly as I mentioned above. I'm also not sure if this is the best approach to take for this situation. I'd love some pointers on better or more "idiomatic" ways to handle this threading issue.
Thanks!