Question

I have a Windows Service (C# 4.0) that picks messages off of a private message queue and for each message sends one or more emails (typically 4 or 5 at most) based on message content.

Message volume is low so I have avoided complexity and left the service sinlge-threaded, but the emails are important so I need to ensure that on an SCM Stop Command any in-process messages/emails are processed/sent before the Stop completes.

In OnStop I am chekcing a static "inProcess" flag representing status and if it is set I am calling ServiceBase.RequestAdditionalTime(120000).

There are 2 problems:

  1. The Stop Command completes immediately with some e-mail unsent, despite the request for 2 minutes.
  2. Even if it worked I am only guessing at how long I should wait.

What is the best way to handle this in a single-threaded service?

Thanks for your help!

Greg

Was it helpful?

Solution

To fully answer, we'd need to see the structure of your message processing loop. But one thing I'm thinking is that the ServiceBase.RequestAdditionalTime() method is used to keep the SCM from complaining if a stop command (or pause, continue, start) takes too long, it doesn't mean your service will wait two minutes before stopping.

Thus, the only thing it truly does is keep the SCM from erroring out on a stop request, if you have a slow stop process.

See MSDN here: RequestAdditionalTime() method

What I'm wondering is if you get called in OnStop() and you set some complete flag, and the processing loop immediately exits when it sees this flag?

If you could post your code it would help me refine this answer, but from the question I wonder if you are expecting the call to wait for 2 minutes to let it process more, but you are setting something to tell the processing loop to stop. If this is not the case I can refine the answer further.

As for how long you should wait, that depends on how critical the emails are and how many are likely to be in the queue, and if they are persisted anywhere so that restarting the service would pick up where they left off.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top