Click here to Skip to main content
16,019,873 members
Articles / Desktop Programming / Win32

Application Recovery and Restart C# Quick Reference

Rate me:
Please Sign up or sign in to vote.
4.95/5 (27 votes)
22 Apr 2010Ms-PL3 min read 57.5K   57   8
Application recovery and restart C# quick reference

Background

Application Recovery and Restart (ARR) is a feature that allows you to prepare for the impossible (?) case where your application crashes or waits forever (“Not Responding”).

The feature lets you “register” for these cases in order to give you the opportunity to save the application data or do some clean up operations, before it ends its life.

This feature exists from Windows Vista, but it seems that not enough people knows it, so let’s see how can anyone use the Windows API Code Pack to easily integrate ARR in their applications.

More information on the feature can be found at Application Recovery and Restart on MSDN.

Step 1 – When to Register?

The first step is quite obvious, but needs to be said nevertheless. You should register to ARR when the application loads and unregister when the application unloads.

C#
public MainWindow()
{
    InitializeComponent();
    ...
    RegisterApplicationRecoveryAndRestart();
}


private void CloseButton_Click(object sender, RoutedEventArgs e)
{
    ...
    UnregisterApplicationRecoveryAndRestart();
    App.Current.Shutdown();
}

The functions RegisterApplicationRecoveryAndRestart and UnregisterApplicationRecoveryAndRestart are my functions which we will see on the next step.

Step 2 – How to Register?

Before using the ARR feature, we check that we’re running on Windows Vista or up by using WindowsAPICodePack CoreHelper.RunningOnVista helper method.

C#
private void RegisterApplicationRecoveryAndRestart()
{
    if (!CoreHelpers.RunningOnVista)
    {
        return;
    }

    // register for Application Restart
    RestartSettings restartSettings = 
        new RestartSettings(string.Empty, RestartRestrictions.None);
    ApplicationRestartRecoveryManager.RegisterForApplicationRestart(restartSettings);

    // register for Application Recovery
    RecoverySettings recoverySettings = 
        new RecoverySettings(new RecoveryData(PerformRecovery, null), KeepAliveInterval);
    ApplicationRestartRecoveryManager.RegisterForApplicationRecovery(recoverySettings);
}

Register for Restart

Then we do two things. First, we register for restart. The Windows Error Reporting component will present the user the restart dialog if the application had an unhandled exception or has been unresponsive for more than 60 seconds.

When registering for restart, we supply an instance of RestartSettings. The first parameter it gets is the command line arguments that will be used for the restart, in case we want to define some special parameters (like “run in safe mode”). The second parameters is an enum that allows us to restrict the restart in some cases, for example, we can set RestartRestriction.NotOnReboot if we don’t want our application to restart if the computer was restarted due to a system update.

Available restrictions are:

RestrictionMeaning
NoneNo restart restrictions
NotOnCrashDo not restart the process if it terminates due to an unhandled exception.
NotOnHangDo not restart the process if it terminates due to the application not responding.
NotOnPatchDo not restart the process if it terminates due to the installation of an update.
NotOnRebootDo not restart the process if the computer is restarted as the result of an update.

Register for Recovery

The second thing we do is register for recovery. This means that if the application will need a restart (from the same reasons as before), what function do we want to run to allow later recovery.

When registering for recovery, we supply an instance of RecoverySettings. The first parameter it gets is the RecoveryData object, which wraps a delegate to be called and some state parameter that will be passed (in this example, null). The second parameter is the keep alive interval, which will be explained shortly.

Implementing the Recovery Function

The recovery function should obey some rules in order to avoid the application getting stuck (again) in the recovery function. You must call ApplicationRestartRecoveryManager.ApplicationRecoveryInProgress every few (mili)seconds (in the example, KeepAliveInterval = 5000). This tells the ARR mechanism, “I know it takes some time, but don’t worry, I’m still alive and working on the recovery stuff”.

Also, at the end of the recovery function, you must call ApplicationRestartRecoveryManager.ApplicationRecoveryFinished with a parameter that indicates whether you succeeded in doing the recovery.

C#
/// <summary>
/// Performs recovery by saving the state 
/// </summary>
/// <param name="parameter">Unused.</param>
/// <returns>Unused.</returns>
private int PerformRecovery(object parameter)
{
    try
    {
        ApplicationRestartRecoveryManager.ApplicationRecoveryInProgress();
                // Save your work here for recovery
        ...

        ApplicationRestartRecoveryManager.ApplicationRecoveryFinished(true);
    }
    catch
    {
        ApplicationRestartRecoveryManager.ApplicationRecoveryFinished(false);
    }

    return 0;
}

Step 3 – How to Unregister

C#
private void UnregisterApplicationRecoveryAndRestart()
{
    if (!CoreHelpers.RunningOnVista)
    {
        return;
    }

    ApplicationRestartRecoveryManager.UnregisterApplicationRestart();
    ApplicationRestartRecoveryManager.UnregisterApplicationRecovery();
}

This is just some cleanup code to properly unregister from Application Recovery and Restart.

That’s it for now,
Arik Poznanski

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer (Senior) Verint
Israel Israel
Arik Poznanski is a senior software developer at Verint. He completed two B.Sc. degrees in Mathematics & Computer Science, summa cum laude, from the Technion in Israel.

Arik has extensive knowledge and experience in many Microsoft technologies, including .NET with C#, WPF, Silverlight, WinForms, Interop, COM/ATL programming, C++ Win32 programming and reverse engineering (assembly, IL).

Comments and Discussions

 
GeneralMy vote of 1 Pin
Singh Vijay Kumar10-Mar-13 18:56
professionalSingh Vijay Kumar10-Mar-13 18:56 
QuestionImplementing ARR in MS Office Application. Pin
Sameerkumar Namdeo20-Feb-13 22:05
Sameerkumar Namdeo20-Feb-13 22:05 
GeneralMy vote of 5 Pin
AhsanS17-Mar-12 23:43
AhsanS17-Mar-12 23:43 
GeneralMy vote of 5 Pin
zenwalker198519-Oct-11 0:08
zenwalker198519-Oct-11 0:08 
QuestionAny way to force restart on a crash without prompting the user? Pin
Adam Volker-Yoblick6-Sep-11 5:31
Adam Volker-Yoblick6-Sep-11 5:31 
Arik,

Great article! We have a tool that we always want to be running, and I'm almost there. I'd like to use ARR, but it seems it always prompts the user to restart the app on a crash. Do you know if there's a way to force an app restart on a crash using ARR, or do I have to write my own custom code to do this?

If I have to write custom code, do you have any suggestions? I've googled it for a bit and it seems there are several ways to do it, but I don't see a standard way.

Thanks for your time,

-Adam
AnswerRe: Any way to force restart on a crash without prompting the user? Pin
Arik Poznanski6-Sep-11 5:36
Arik Poznanski6-Sep-11 5:36 
GeneralGreat article, I suppose it works for Windows7 as well Pin
moragos26-Apr-10 20:00
moragos26-Apr-10 20:00 
GeneralRe: Great article, I suppose it works for Windows7 as well Pin
Arik Poznanski26-Apr-10 20:29
Arik Poznanski26-Apr-10 20:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.