Skip to content
Philemon Eichin edited this page Feb 12, 2018 · 2 revisions

Single Instance Manager

Behavior

A single instance application has only one process running at a time. If the users starts a second process the second process should inform the already running instance and submit the command line parameters. After that the second process should exit and the first instance will process the command line arguments.

Implementation

This single instance manager follows the approach given here and uses a system wide Mutex to determine if there is an other running instance and if, submit the command line parameter through a named pipe.

Usage

If you are in a WinForms or Console application use follow this snipped:

public static int Main(string[] args){
    // submit an optional guid. If no parameter is given the entry assembly name is used.
    var instanceManager = SingleInstanceManager.CreateManager("{GUID}");
        if(instanceManager.RunApplication(args)){
            // Register an event handler for second instances
            instanceManager.SecondInstanceStarted + = OnSecondInstanceStarted;
            // perform other bootstrap operations
            // ...
            // Close the manager, so other instances can start in a valid state       
            instanceManager.Shutdown();
        }
        // perform exit logic
    }

In an WPF project use this snipped

public class Application : App
{
    static readonly Guid AppGuid = new Guid(/*Your guid goes here*/);

    // the instance of the single application manager
    private SingleInstanceManager.SingleInstanceManager manager;

    protected override void OnStartup(StartupEventArgs e)
    {
        // create an instance of the manager
        manager = CreateManager(AppGuid.ToString());

        if (manager.RunApplication(e.Args))
        {
           instanceManager.SecondInstanceStarted + = OnSecondInstanceStarted;
           base.OnStartup(e);               
        }
        else
            Environment.Exit(0); // exit the second instance
    }

    protected override void OnExit(ExitEventArgs e)
    {
        manager.Shutdown();
        base.OnExit(e);
    } 
}
Clone this wiki locally