Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a loop in a Windows service without using the Timer

Tags:

I want to call a Business layer method from a Windows service (done using C# and .NET) after every 10 seconds. However, i dont want to use the Timer_Elapsed event since it starts up another thread/process if the first thread/process is still running. I just need a single threaded approach, since multiple calls to the same Business method creates unwanted complications.

So i added a do--while loop in the on_start. I know this is not the correct way since it spawns this process which becomes an orphan if the service is shut down.

How can i approach this problem ?

Regards, Chak

like image 290
Chakra Avatar asked Jan 09 '10 08:01

Chakra


People also ask

Does Windows service run continuously?

Once the win service is started then this process will run continuously in background.

How do I run a Windows service once a day?

Just create a regular console app, then use the Windows scheduler to run your program at 6am. A service is when you need your program to run all the time.


1 Answers

There's another way to get timed execution, the WaitHandle.WaitOne() method provides a timeout argument. That works very nicely in a service as it lets you implement the need to stop the service and periodic execution in a single method call. The template looks like this:

    Thread Worker;     AutoResetEvent StopRequest = new AutoResetEvent(false);      protected override void OnStart(string[] args) {         // Start the worker thread         Worker = new Thread(DoWork);         Worker.Start();     }     protected override void OnStop() {         // Signal worker to stop and wait until it does         StopRequest.Set();         Worker.Join();     }     private void DoWork(object arg) {         // Worker thread loop         for (;;) {             // Run this code once every 10 seconds or stop right away if the service              // is stopped             if (StopRequest.WaitOne(10000)) return;             // Do work...             //...         }     } 
like image 65
Hans Passant Avatar answered Oct 14 '22 16:10

Hans Passant