Use a Windows Service with a Thread

Problem

You want to create a Windows service that performs some type of long-running task continuously.

Solution

Create a new thread when the service is started, and perform all your work on that thread.

Discussion

As explained earlier, the OnStart method is used to set your Windows service processing in motion, but it can’t perform the work directly itself. One of the most common design patterns is to use the OnStart method to create and start a new thread. The OnStop method can then terminate this thread.

This thread can process continuously, using a loop if it needs to repeat the same work. In addition, you might want to use a Boolean member variable to allow the OnStop method to signal a polite stop (a technique ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.