I love .Net Services. Its a handy way to create background processes, and they work beautifully in both Windows and Linux (thanks to Mono!).
However, every time I create one I find myself writing a lot of the same code with minor variations:
- OnStart: start a worker thread, make it sure it didn’t die, exit
- OnStop: try to stop the worker thread nicely, wait, abort it, exit
Depending on how “nice” you want to be to your worker thread, you can come up with some pretty crazy code to deal with your worker thread (volatile class variables, wait loops, etc.).
I’ve created a basic template for new .Net Services:
It was inspired by a service I wrote to read a firewall log file into a database:
The template doesn’t contain any complex worker thread stopping code. Lumberjack uses a mess of methods to try and nicely stop the worker. I’m not sure what Lumberjack does is really any more useful than just using Abort(), but I didn’t want to leave a database connection open.
Both zips contain MonoDevelop solution files, although Main.cs is the only important file in both of them.
The other highlight of both the template and Lumberjack is the SmartLog() method which logs to syslog in Linux and the Event Log in Windows. Although you probably have to comment out the syslog reference to build the source in Windows.
I’m sure I’ll update and keep using this code in the future… I need to find some way to manage my mini-projects and code snippets… any ideas?