Skip to content
Bruno Sonnino
Menu
  • Home
  • About
Menu

Multi Instancing in UWP

Posted on 20 June 2018

One thing that went unnoticed in the last post is that the console app is multi-instance: if you click in the live tile or in the start menu, instead of bringing the same app to the front, you are opening a new window and running a new instance of it. This is something new for UWP apps: until now, you could only have one instance of the app running in your machine. While this works for many apps, when you are developing an LOB app, for example, you may need to open more than one instance and that can be limiting. The SDK released in the Aril 2018 update allow you to create multi instanced apps.

Single instance apps

The default UWP apps have a single instance. When you activate it for the first time, it opens the main window and runs the app. After the second call, the same app is activated and you can handle the activation in the OnLaunchedmethod, like this:

private int _activationNo;
/// <summary>
/// Invoked when the application is launched normally by the end user.  Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // Create a Frame to act as the navigation context and navigate to the first page
        rootFrame = new Frame();

        rootFrame.NavigationFailed += OnNavigationFailed;

        if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application
        }

        // Place the frame in the current Window
        Window.Current.Content = rootFrame;
    }

    if (e.PrelaunchActivated == false)
    {
        if (rootFrame.Content == null)
        {
            // When the navigation stack isn't restored navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }

        if (rootFrame.Content is MainPage page)
            page.MainText = 
                $"Activation# {++_activationNo}";
        // Ensure the current window is active
        Window.Current.Activate();
    }
}
C#

This way, you will see the activation number in the main page for the app. The app continues to have a single page, but you can control the number of times it's activated. One other way to handle this is to open multiple windows, one for each activation. It is done like this:

private int _activationNo;
/// <summary>
/// Invoked when the application is launched normally by the end user.  Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // Create a Frame to act as the navigation context and navigate to the first page
        rootFrame = new Frame();

        rootFrame.NavigationFailed += OnNavigationFailed;

        if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application
        }

        // Place the frame in the current Window
        Window.Current.Content = rootFrame;
    }

    if (e.PrelaunchActivated == false)
    {
        if (rootFrame.Content == null)
        {
            // When the navigation stack isn't restored navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter
            rootFrame.Navigate(typeof(MainPage), e.Arguments);

            if (rootFrame.Content is MainPage page)
                page.MainText =
                    $"Activation# {++_activationNo}";
            // Ensure the current window is active
            Window.Current.Activate();
        }
        else
        {
            CreateNewView();
        }
    }
}

private async void CreateNewView()
{
    CoreApplicationView newView = CoreApplication.CreateNewView();
    int newViewId = 0;
    await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        Frame frame = new Frame();
        frame.Navigate(typeof(MainPage), null);
        Window.Current.Content = frame;
        if (frame.Content is MainPage page)
            page.MainText =
                $"Activation# {++_activationNo}";
        // You have to activate the window in order to show it later.
        Window.Current.Activate();

        newViewId = ApplicationView.GetForCurrentView().Id;
    });
    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
}
C#

The process is similar to the previous ones, but there is a difference: for the first activation, it fills the main window, and if not, it creates a new window with the CreateNewView method, then fills its content in the same way it did for the main window. After the window and the view are created and activated, we call ApplicationViewSwitcher.TryShowAsStandaloneAsync to show it. This will show the new window for the app.
MultiWnd
This arrangement works fine, but there is a problem, here: all windows are in the same process and, if you have a problem in one of them, all will crash. This may not be what you want, and it's changed in the April 2018 update - you can have multi-instance UWP apps.

Multi-Instance apps

The main difference is the SupportsMultipleInstances attribute in the package.appxmanifest file, in the Application node:

<Application 
  Id="App"
  Executable="$targetnametoken$.exe"
  EntryPoint="MultiInstance.Program"
  desktop4:SupportsMultipleInstances="true" 
  iot2:SupportsMultipleInstances="true">
XML

The desktop4 and iot2 namespaces are defined in the Package node:

<Package
  xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
  xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5" 
  xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4" 
  xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" 
  IgnorableNamespaces="uap mp uap5 iot2 desktop4">
XML

Once you put these in your package.appxmanifest, your application will be multi-instanced:

MultiInstance
If you don't want to add this data manually, you can install the Multi-Instance templates, created by Microsoft. In Visual Studio, go to Tools/Extensions and Updates and install the Multi-Instance template:
MultiInstanceTemplate
Once you do that, you will get two new UWP templates, the Multi-Instance UWP App and Multi-Instance UWP Redirection App:
NewUwpTemplates
The Multi-Instance UWP App template does what we did before: creates a blank app with the new attribute. The Multi-Instance Redirection UWP App is a bit more complex. Sometimes you want to handle how multi instancing works and call a specific instance. In this case, the template generates a Program.cs file with a Main method, where you can handle the redirection.

public static class Program
{
    // This project includes DISABLE_XAML_GENERATED_MAIN in the build properties,
    // which prevents the build system from generating the default Main method:
    //static void Main(string[] args)
    //{
    //    global::Windows.UI.Xaml.Application.Start((p) => new App());
    //}

    // This example code shows how you could implement the required Main method to
    // support multi-instance redirection. The minimum requirement is to call
    // Application.Start with a new App object. Beyond that, you may delete the
    // rest of the example code and replace it with your custom code if you wish.

    static void Main(string[] args)
    {
        // First, we'll get our activation event args, which are typically richer
        // than the incoming command-line args. We can use these in our app-defined
        // logic for generating the key for this instance.
        IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

        // In some scenarios, the platform might indicate a recommended instance.
        // If so, we can redirect this activation to that instance instead, if we wish.
        if (AppInstance.RecommendedInstance != null)
        {
            AppInstance.RecommendedInstance.RedirectActivationTo();
        }
        else
        {
            // Define a key for this instance, based on some app-specific logic.
            // If the key is always unique, then the app will never redirect.
            // If the key is always non-unique, then the app will always redirect
            // to the first instance. In practice, the app should produce a key
            // that is sometimes unique and sometimes not, depending on its own needs.
            uint number = CryptographicBuffer.GenerateRandomNumber();
            string key = (number % 2 == 0) ? "even" : "odd";
            var instance = AppInstance.FindOrRegisterInstanceForKey(key);
            if (instance.IsCurrentInstance)
            {
                // If we successfully registered this instance, we can now just
                // go ahead and do normal XAML initialization.
                global::Windows.UI.Xaml.Application.Start((p) => new App());
            }
            else
            {
                // Some other instance has registered for this key, so we'll 
                // redirect this activation to that instance instead.
                instance.RedirectActivationTo();
            }
        }
    }
}
C#

From the comments in the file, you can see that you can get the default behavior just by using this code in the Main method:

static void Main(string[] args)
{
    global::Windows.UI.Xaml.Application.Start((p) => new App());
}
C#

The key will be linked to the instance you want. For example, if you generate only different keys, new instances will be opened, and if you generate only one key, the first instance will be called. You can control how many instances you want and which ones you want to activate by using the keys you generate. For example, this code will allow you to have three instances open and will call them in a round-robin scheme:

static void Main(string[] args)
{
    // First, we'll get our activation event args, which are typically richer
    // than the incoming command-line args. We can use these in our app-defined
    // logic for generating the key for this instance.
    IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

    // In some scenarios, the platform might indicate a recommended instance.
    // If so, we can redirect this activation to that instance instead, if we wish.
    if (AppInstance.RecommendedInstance != null)
    {
        AppInstance.RecommendedInstance.RedirectActivationTo();
    }
    else
    {
        // Define a key for this instance, based on some app-specific logic.
        // If the key is always unique, then the app will never redirect.
        // If the key is always non-unique, then the app will always redirect
        // to the first instance. In practice, the app should produce a key
        // that is sometimes unique and sometimes not, depending on its own needs.
        var instanceNo = GetInstanceNo();
        string key = instanceNo.ToString();
        var instance = AppInstance.FindOrRegisterInstanceForKey(key);
        if (instance.IsCurrentInstance)
        {
            // If we successfully registered this instance, we can now just
            // go ahead and do normal XAML initialization.
            global::Windows.UI.Xaml.Application.Start(p => new App());
        }
        else
        {
            // Some other instance has registered for this key, so we'll 
            // redirect this activation to that instance instead.
            instance.RedirectActivationTo();
        }
    }
}

private static int GetInstanceNo()
{
    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
    var instanceNo = 0;
    object data = localSettings.Values["instanceNo"];
    if (data != null)
    {
        instanceNo = ((int)localSettings.Values["instanceNo"] + 1) % 3;
    }

    localSettings.Values["instanceNo"] = instanceNo;
    return instanceNo;
}
C#

In this case, we are keeping it simple, but we can make something more complex here. For example, we can activate some instance depending on the parameters passed to the application:

static void Main(string[] args)
{
    // First, we'll get our activation event args, which are typically richer
    // than the incoming command-line args. We can use these in our app-defined
    // logic for generating the key for this instance.
    IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();
    // In some scenarios, the platform might indicate a recommended instance.
    // If so, we can redirect this activation to that instance instead, if we wish.
    if (AppInstance.RecommendedInstance != null)
    {
        AppInstance.RecommendedInstance.RedirectActivationTo();
    }
    else
    {
        // Define a key for this instance, based on some app-specific logic.
        // If the key is always unique, then the app will never redirect.
        // If the key is always non-unique, then the app will always redirect
        // to the first instance. In practice, the app should produce a key
        // that is sometimes unique and sometimes not, depending on its own needs.
        string key = "MainInstance";
        if (args.Length > 0)
            key = args[0];
        var instance = AppInstance.FindOrRegisterInstanceForKey(key);
        if (instance.IsCurrentInstance)
        {
            // If we successfully registered this instance, we can now just
            // go ahead and do normal XAML initialization.
            global::Windows.UI.Xaml.Application.Start(p => new App());
        }
        else
        {
            // Some other instance has registered for this key, so we'll 
            // redirect this activation to that instance instead.
            instance.RedirectActivationTo();
        }
    }
}
C#

The key for the instance depends on the first parameter passed to the app. If we change our package.appxmanifest to add an ExecutionAlias, we can open a console window and call the app with a parameter:

<Package
  xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
  xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5"
  xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4" 
  xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" 
  IgnorableNamespaces="uap mp desktop4 iot2 uap5">

    ....

   <Extensions>
     <uap5:Extension
       Category="windows.appExecutionAlias"
       Executable="MultiInstance.exe"
       EntryPoint="MultiInstance.App">
       <uap5:AppExecutionAlias>
         <uap5:ExecutionAlias Alias="MultiInstance.exe" />
       </uap5:AppExecutionAlias>
     </uap5:Extension>
   </Extensions>
 </Application>
XML

Now, we can handle different instances of our app. If we want to process the arguments (for example, to open a different file depending on the passed parameter), we can do it in the App.xaml.cs. Please note that the OnLaunched method is not called when the app is activated from the command line. In this case, you must override the OnActivated method and process the arguments from there:

protected override void OnActivated(IActivatedEventArgs args)
{
    var arguments = (args as CommandLineActivatedEventArgs)?.Operation.Arguments;
    Frame rootFrame = Window.Current.Content as Frame;
    if (rootFrame == null)
    {
        rootFrame = new Frame();
        Window.Current.Content = rootFrame;
    }

    if (rootFrame.Content == null)
    {
        rootFrame.Navigate(typeof(MainPage), 
            $"Activated Kind {args.Kind}\nArguments: {arguments}");
    }
    Window.Current.Activate();
}
C#

The processing of the arguments in the main page are done in the OnNavigatedTo method in MainPage.xaml.cs:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var param = e?.Parameter;
    MainTxt.Text = param?.ToString() ?? "";
    base.OnNavigatedTo(e);
}
C#

Now, if we open a command line window and type something like MultiInstance "this is a test", the program will open a new instance with the arguments:
MultiInstanceArgs

Conclusions

As you can see, this new feature brings a lot of flexibility to your app. You already had the possibility to create many windows and now you can even create new instances and redirect the app to the right instance, depending on how the app is launched.

The full source code is available in http://github.com/bsonnino/MultiInstanceUWP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • May 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • June 2024
  • November 2023
  • October 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • October 2020
  • September 2020
  • April 2020
  • March 2020
  • January 2020
  • November 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • June 2017
  • May 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • October 2015
  • August 2013
  • May 2013
  • February 2012
  • January 2012
  • April 2011
  • March 2011
  • December 2010
  • November 2009
  • June 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • July 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • Development
  • English
  • Português
  • Uncategorized
  • Windows

.NET AI Algorithms asp.NET Backup C# Debugging Delphi Dependency Injection Desktop Bridge Desktop icons Entity Framework JSON Linq Mef Minimal API MVVM NTFS Open Source OpenXML OzCode PowerShell Sensors Silverlight Source Code Generators sql server Surface Dial Testing Tools TypeScript UI Unit Testing UWP Visual Studio VS Code WCF WebView2 WinAppSDK Windows Windows 10 Windows Forms Windows Phone WPF XAML Zip

  • Entries RSS
  • Comments RSS
©2025 Bruno Sonnino | Design: Newspaperly WordPress Theme
Menu
  • Home
  • About