views:

270

answers:

2

My windows service is a data server with substantial cache. During service OnStop I save the cache so that no data is lost. Saving cache may take several minutes so to prevent windows service manager from timeout I use SetServiceStatus Win32 callback:

this.serviceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
this.serviceStatus.checkPoint = 1;
this.serviceStatus.waitHint = 60000;
SetServiceStatus(Process.GetCurrentProcess().Handle, ref this.serviceStatus);

That works fine.

I have also set CanShutdown to true and added OnShutdown so that service would be system shutdown proof. Here I effectively do the same thing as in OnStop:

protected override void OnShutdown()
{
    this.OnStop(); 
    base.OnShutdown();
}

That does not work too good. When system shuts down, when cache is being saved I get "The device is not ready". This suggests that Windows aborts service before it is done stopping / shutting down. Preventing that with SetServiceStatus apparently does not work.

How do I get more time (delay reboot) to get saving done?

Any suggestions welcome.

A: 

Using ManualResetEvent might be the trick.

dboarman
I do not see how ManualResetEvent would be of any benefit here. I am not in control of thread requesting service shutdown and I do not want to synchronize with it anyway. All I want it to prevent Windows from killing my service before OnShutdown ends. Something like SetServiceStatus does for OnStop.
Maciej
Since ManualResetEvent basically gives you a way to make threads wait, I thought it would help. I can see your point, though - if you can't detect when another process is going to shut down your service. Like @marc.d suggest, though, consider saving this cache more often? He has a very valid point.
dboarman
It is an extreme system. I am saving cache more often but there can be too much data. It is a write cache. Data can come much faster than I can save it on-the-fly and it is a constant stream. The trick is that cache re-arranges data (from horizontally to vertically) so it is much more efficient to save it thus I need to accumulate some data before I can save it. So it is possible that when system shutdown occurs I could have no data at all or quite a lot of it.
Maciej
A: 

After some testing it looks that it was a problem with the system rather than with my service.

Maciej