Search code examples
c#windows-servicesdisaster-recovery

How can I make a windows service run some code if it had to restart after a crash?


Let's say a windows service crashes, and automatically restarted due to some recovery options. I want to run some code in the program (C#) that will do some network action (send an alert that it shut down) whenever this happens.

Is there an event I can apply or code I can have run after that occurs?

Thanks!


Solution

  • In this situation what I would do is instead of having something that gets written out when the program fails, have the program write out some kind of record to persistent storage that it then deletes if it detects a clean shutdown is being done.

    public partial class MyAppService : ServiceBase
    {
        protected override void OnStart(string[] args)
        {
            if(File.Exists(Path.Combine(Path.GetTempPath(), "MyAppIsRunning.doNotDelete"))
            {
                DoSomthingBecauseWeHadABadShutdown();
            }
            File.WriteAllText(Path.Combine(Path.GetTempPath(), "MyAppIsRunning.doNotDelete"), "");
            RunRestOfCode();
        }
    
        protected override void OnStop()
        {
            File.Delete(Path.Combine(Path.GetTempPath(), "MyAppIsRunning.doNotDelete"));
        }
    
        //...
    }
    

    This could easily have the file swapped out with a registry entry or a record in a database.