miércoles, 14 de octubre de 2009

Windows Service + Threading

Even if the use of a timer is the usual approach you take when creating a windows service I have a special affection for Threads.The last couple of days I've been trying to do something like this:

//This code goes in the Service.cs:
// My class that contains all the service logic

MyThread myThread;
// the thread that will do the work private
Thread workerThread;
...

protected override void OnStart(string[] args) {
// set flag to indicate worker thread is active
myThread.ExecuteService = true;
// Create worker thread; this will invoke the WorkerFunction
workerThread = new Thread(new ThreadStart(myThread.WorkerFunction));
// start the thread workerThread.Start();
}

protected override void OnStop() {
// flag to tell the worker process to stop
myThread.ExecuteService = false;
// give it a little time to finish any pending work
workerThread.Join();
}

//This code goes on myThread class:


public void WorkerFunction() {
do{
...
} while(ExecuteService);
}

However with this code everytime after the service just started the service got stopped. Without a clue about what could the problem be I decided to get some wisdom from Google and run into this page: Windows Service Basics

The article (no so basic by the way) presents three different approches (2 of them includes threads =) ) when creating a Windows Service.With a couple of modifications to my code everything run as supposed to:

// This is a flag to indicate the service status
private bool executeService = false;
// My class that contains all the service logic

MyServiceClass myService;
// the thread that will do the work
private Thread workerThread;
...

protected override void OnStart(string[] args) {
// set flag to indicate worker thread is active
executeService = true;
// Create worker thread

workerThread = new Thread(new ThreadStart(DoWorkFunction));
// start the thread
workerThread.Start();
}

protected override void OnStop() {

// flag to tell the worker process to stop
executeService = false;
// give it a little time to finish any pending work
workerThread.Join(new TimeSpan(0,2,0));
}

public void DoWorkFunction() {

do{
myService.WorkerFunction();
} while(executeService);
Thread.CurrentThread.Abort();
}

The way I like it... nice & easy!

I really recommend to read the whole article from the en.csharp-online.net guys. It helped me with my problem and learned a couple of things I wasn't aware of.

No hay comentarios:

Publicar un comentario