I have a Windows Service which is basically accessing a mailbox and reading the emails. I am trying to figure out the best way to check the mailbox every x seconds.
One method is to just call Thread.Sleep, then call the Start Method again, e.g.
protected override void OnStart(string[] args)
{
// get config settings
CheckMailbox();
}
public void CheckMailbox()
{
int x = 5000;
// do stuff
Thread.Sleep(x);
CheckMailbox();
}
Not sure if this is the best way to go about it. To then further explore this, I understand that you can call a Windows Service by exposing the Service via WCF. In this case, if a web application called the Process to start, there would be conflicting Threads am I correct? How would I then deal with that? Would I have to create a new thread each time and put it in a queue?
Sleeping is usually a bad idea. Apart from anything else, it means that you won’t respond to the Stop event quickly.
You should use a
Timer. There are two which are appropriate for services:In each case you basically say what you want to happen each time the timer “ticks” and when you want it to fire.
My threading tutorial has a section explaining some of the differences between available timers.
I’m not sure about your WCF question, but I don’t think your web service would be explicitly starting the service – it would just be contacting it via WCF. Yes, you’d potentially need to be careful about threads. Exactly what you’ll need to be careful of will depend on what the WCF service is exposing.