Windows Services: OnStart loop - do I need to delegate?
Asked Answered
D

2

21

I've got a windows service which scans a folder every n seconds for changes. I'm getting "the service did not respond to the start command in a timely fashion" when trying to start it up.

I've got a loop setting off in OnStart like so:

 public void OnStart(string[] args)
 {
    while (!_shouldExit)
    {
        //Do Stuff

        //Repeat
        Thread.Sleep(_scanIntervalMillis);
    }
 }

Is this what is causing the error? Should I delegate this method?

Dwyer answered 16/3, 2009 at 10:52 Comment(0)
N
41

OnStart should only start the work; it isn't responsible for doing it. This typically means spawning a new thread to do the actual work. It is expected that OnStart completes promptly. For example:

    public void OnStart(string[] args) // should this be override?
    {
        var worker = new Thread(DoWork);
        worker.Name = "MyWorker";
        worker.IsBackground = false;
        worker.Start();
    }
    void DoWork()
    {
        // do long-running stuff
    }
Nephoscope answered 16/3, 2009 at 10:57 Comment(5)
@Bizorke if you mean terminated abruptly: it is simply killed mid flow, the same as terminating any process. If you mean "stopped", then: whatever your code tells it to doNephoscope
@MarcGravell Is there a specific that worke.IsBackground is false? thus that the thread is a foreground thread?Nitroso
@ThomasE if IsBackground is true, then that thread will not keep the process alive. If there are no foreground threads in a process - it tends to get killed by the OS. This might work differently for service apps, but usually when I write a service I write a dual "can run as a service or from the command-line" exe (which makes it really easy to debug), so: having it not get terminated as soon as Main() exits is a definite advantage.Nephoscope
tnx. thought there was a specific reason why you choose false but wasn't sure why exactly. tnx there for the clarification why you chose that approach.Nitroso
@MarcGravell Are there any related guidelines or caveats regarding the service OnStop() method?Northwestward
S
6

The OnStart method shouldn't block. You need to spawn a worker thread that will do the job. You could also take a look at the FileSystemWatcher class to scan for file system change notifications.

Shanly answered 16/3, 2009 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.