Tutorial :How to keep a windows service going (.Net)


I'm new to windows services, so pardon the basic nature of this post.

I've been tasked with updating an existing service and had some questions about how they work and keep running in the background. I assume a loop of some sort is usually in play, but in the case below I'm not sure how it works and why it doesn't stop in a short amount of time.

In brief, this service creates a System.IO.FileSystemWatcher object in its InitializeComponent() section and establishes an event handler for its Created event.

In the service's OnStart method(), a thread is created and started. This thread loops and instructs the FileSystemWatcher object to look at a particular directory, and establishes various settings and options for the FileSystemWatcher. It's not an infinite while() loop by any means; it does some math involving a user supplied timeout value and a wait time for sleeping, but in every case it will exit eventually.

The FileSystemWatcher event handler referred to above, in turn, puts the newly created file that triggered the event onto a thread-safe queue, then either creates a new or uses an existing thread to process the queued file. The queue-processing code uses a loop to check the queue and remove any items from it and process them. When there are no items in the queue, the while loop ends and the method exits.

These file created events are pretty few and far between, so I can't see how either loop would be so busy as to remain running all the time. By this logic the service should stop, or so I'd think. But it never does, it's always running.

Is there some invisible message pump in a windows service that keeps it going until the OnStop or pause events are fired?

I hope this makes sense, and apologies if my descriptions didn't. I'd be happy to elaborate further if you think it might help. Thanks for your explanations here.


You don't need that loop.

Consider your business class creating your FileSystemWatcher and signing for it's events, and all other stuff your need.

On ServiceBase.OnStart override, you'll create an instance from your business class and to place it into a class level variable (a field, for instance).

On ServiceBase.OnStop override, you'll clean anything you need.

And that's it. You don't need to deal with background threads or anything else.


The FileSystemWatcher event callbacks occur in a separate thread from the system thread pool. So even if the thread that created the watcher dies the events will still occur.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »