Kat
Kat

Reputation: 2500

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!

Upvotes: 1

Views: 130

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

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.

Upvotes: 3

Viru
Viru

Reputation: 2246

You can subscribe to below event which will fire no matter in which thread the exception occurs..

AppDomain.CurrentDomain.UnhandledException

Sample implementation

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
 // log the exception ...
}

Upvotes: 2

Related Questions