Reputation: 35
I have a service which creates a FileSystemWatcher inside OnStart and I want the service to end only after a file is created
So I have this code
protected void OnStart()
{
try
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = WatchPath;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = false;
watcher.Changed += OnCreated;
watcher.EnableRaisingEvents = true;
logEvents.Write(MyLogClass.LogLevel.Info, "Watcher created");
}
}
catch (Exception ex)
{
logEvents.Write(MyLogClass.LogLevel.Info, ex.Message);
}
if (finished)
{
OnStop();
}
}
The bool "finished" is only set to true in the last line of OnCreated
private void OnCreated(object sender, FileSystemEventArgs e)
{
//Here I do all the stuff I need and then:
finished = true;
}
But even when OnCreated is not executed the service ends and I get:
"The program - has exited with code 0 (0x0)."
I've tried calling OnStop() in different parts of the code but the same thing happens anyways. I'd like the service to stay still until a given file is created and to start over when OnCreated is done, but I don't know what's wrong in this.
Upvotes: 0
Views: 63
Reputation: 239754
A FileSystemWatcher
, by itself, isn't enough to keep a process running. When no events are being serviced, no threads are required, and even when one is required it'll be a background thread.
What a process needs to stay running is a foreground thread. It doesn't matter what that thread is doing, so long as at least one exists.
It doesn't look like you have any useful work for such a thread to do - but you need one. I suggest you create a thread that just waits for a ManualResetEvent
to become set. You then use that, rather than your finished
variable, to indicate when you want the service to shut down.
At that point, the foreground thread exits, no foreground threads are left, the process shuts down and the service becomes stopped.
Note that you have to create a new thread for this waiting work. The thread on which OnStart
(and OnStop
) is called doesn't "belong" to you. It's a thread that services the Service Control Manager, and you need to let it do that.
Upvotes: 2
Reputation: 9640
Your code is executing once and then ending.
You need a loop with a sleep timer around the main code to keep it alive. And in here embed your check for finished.
Edit: As mentioned in the comments. I missed that you were doing this in OnStart. The loop shouldn't be done here otherwise windows will think that you service failed to start. So you will also need to refactor this.
Upvotes: 1