Understanding Windows Runtime

Discussion in 'C#' started by MinalS, Apr 14, 2015.

  1. MinalS

    MinalS New Member

    Jul 8, 2014
    Likes Received:
    Trophy Points:
    Windows Runtime is a replacement for the Windows API. It provides user with managed classes that are used from C# to access the system features. The runtime is a native API. It is easy to be used as the .NET framework class.


    The classes present in the Windows Runtime are grouped within namespaces. It is similar to .NET framework. The Windows Runtime namespace start with Windows namespace.

    Some of the namespaces used in the Windows Runtime are as mentioned below:
    1. Windows.System : The namespace and the sub namepsaces contain a Launcher class for launching applications.
    2. Windows.Foundation: The namespace contains subnamepsaces for collections, diagnostics and metadata
    3. Windows.ApplicationModel: It has subnamespaces for managing the store licensing
    4. Windows.Graphics: It is useful for images and printing
    5. Windows.Data: It contains classes for XML, HTML, JSON, and PDF
    6. Windows.Storage: It is useful for reading and writing files. The namespace contains classes as StorageFile and StorageFolder. There are stream, file pickers, and compression classes


    The user can access metadata information similar to the .NET application in the Windows runtime. The format of the metadata is similar. User can use the ildasm to read the metadata of the runtime libraries.

    The Object browser is an easy way to look at the classes from the runtime by selecting Windows as the browsing scope. The windows.wind files present in the <Program Files (x86) > \ Windows Kits \ 8.1 \ References \ CommonConfiguration \ Neutral are used.

    Windows Runtime Type

    Windows Runtime types have an interaction with different languages. When user passes a string to the runtime method, a new string is not created for every method call.

    The different categories of runtime are as mentioned below:
    1. Strings: The strings in the runtime are defined as handlers known as HSTRING. It is a reference to the first character to the string. The HSTRING is added to the buffer of the string type for addressing the complete string. In runtime, the strings are immutable.
    2. Arrays: The array as Int 32 [ ] can be used as the collection.
    3. Structs: They are present in the WinRT and are different from the .NET struct type. A .NET struct contains implementation of interfaces.
    4. Generic Interfaces: The runtime supports generic interfaces. The IIterable<T> helps user to enumerate the collection. IVector<T> is used to represent the random access to the collection.
    5. Runtime classes: The classes such as Windows.Storage.StorageFile are included in the runtime. The Storage file implements IStorageFile, IStorageFileItem, IInputStreamReference

    Components for Windows Runtime

    There are some differences when user creates Windows Runtime components with the Visual Studio. It offers a Windows Runtime Component template along with the application template.

    When the runtime components are created, the public class must be sealed. The UI component does not require the sealed type.

    The Windows Runtime defines collection interfaces that map automatically to the .NET collection interfaces.
    1. The IIterable <T> collection interface maps to the IEnumerable <T> in .NET
    2. The IIterator <T> collection interface maps to the IEnumerator <T> in .NET
    3. The IVector <T> collection interface maps to the IList <T> in .NET
    4. The IMap <K, V> collection interface maps to the IDictionary <K,V> in .NET
    5. The IMapView <K, V> collection interface maps to the IReadOnlyDicitonary <K, V> in .NET
    When the runtime components are created, user needs to return an interface.

    The following code snippet demonstrates the runtime component.
    public IList<string> GetStringData()
        return new List<string> { “new”, “old” };
    In the above code, the IList<string> maps to the IVector<T> of the runtime. The List<string> cannot be mapped directly.


    In Windows Runtime, the Windows.Storage.Streams namespace provides a concrete stream classes. The classes such as FileInputStream, FileOutputStream, RandonAccessStream, DataReader, and DataWriter are provided. The classes are based on interfaces. The runtime components always need interfaces for streams as IInputStream, IOutputStream and IRandonAcessStream. The interfaces can be mapped using the extension methods defined in the WindowsRuntimeStreamExtensions class.

    The following code snippet demonstrates the Stream object for an IInputStream.
    public void Stream1 ( IInputStream inputstream )
        var reader = new StreamReader ( InputStream.AsStreamForRead());

    Delegates and Events

    The delegates and events are similar to .NET but the implementation is not similar. The events can only be Windows runtime delegate type. An event cannot be of the EventHandler type. It uses the EventHandler<object>.

    The WindowsRuntimeMarshal class is used for implementing the events. The AddEventHandler and RemoveEventHandler are used for adding and removing handlers.

    Async operations

    The async operations uses the Task objects. The async methods that does not have a return value and return Task. The async methods return Task<T>. The async methods with Windows runtime are based on the interface IAsyncAction and IAsyncOperation<T>/.

    The async and await keywords are used with the async methods. The XmlDocument class from the namespace Windows.Data.Xml.Dom is used. The method LoadFromUriAsync returns the IAsyncOperation <XmlDocument>.

    Consider the following code snippet to demonstrate the async operations.
    private async Task <string> XmlDemo()
        Uri uri =new Uri (“http://www.google.com/downloads/Student.xml”);
        XmlDocument doc = await XmlDocument.LoadFromUriAsync(uri);
        return doc.GetXml();
    private async void OnXml(object sender, RoutedEventArgs e)
        txt1.Text = await XmlDemo();
    The async method does not return a Task. The method is written as the following two code snippets. If the method does not return a value, it needs to return IAsyncAction. The following code snippet demonstrates the functionality.
    public IAsyncAction Task1()
        return Task.Run(async() => 
            await Task.Delay(2000);
        }) .AsAsyncAction();
    The async method returns a value the IAsyncOperation<T> needs to return. The code to demonstrate the AsAsyncOperation for converting the Task<T> to IAsyncOperation<T> is as shown below:
    public IAsyncOperation<int> TaskReturn(int a, int b)
        return Task<int>.Run<int>(async() =>
            await Task.Delay(3000);
            return a+b;

    Windows Store Apps

    The Visual Studio application provides user with various templates that are useful for creating the store apps. The Blank App template contains an empty page. The Grid App template consists of pages used for displaying the data. The Hub App makes use of a Hub control. The Split App contains two pages to navigate the item list. The runtime component creates a library that is reused with the store app projects from different languages.

    Life Cycle of an Application

    In the life cycle of a desktop application, the user has the control to start and end an application. The Task Manager is also useful in killing the hanged application.

    In the Windows App store application, the user does not stop any application. The application is started by clicking the tile. It is similar to the desktop application. When the user starts an application it is in running mode. Once the new application is started, the previous application is sent to the suspended mode. The use of battery is limited in the suspended mode. The application is present in the memory but cannot be used by other users.

    When the user moves back to the first application, the application is resumed from the suspended mode and is placed in the foreground. If there are low memory resources, the windows terminate the suspended applications.

    Application Execution States

    The ApplicationExecutionState enumeration is used for defining the state of an application. This enumeration defines states as Not Running, Running, Suspended, Terminated, and ClosedByUser. The application needs to move to the to the position where they left it initially.

    The OnLaunched method of the App class provides user with the PreviousExecutionState property of the LaunchActivatedEventArgs argument. The previous execution state is NotRunning if the application is being started for the first time or system reboots or stops the process. The application is in running state if it was already running when user activated it.

    To demonstrate the navigation of state, the application has pages as Page1 and Page2 along with the Main Page.

    The following code snippet demonstrates the navigation to Page2.

    private void OnGotoPage2(object sender, RoutedEventArgs e)

    Suspension Manager

    The SuspensionManager class has a SaveAsync method that is used to save both frame navigation and session state. For saving the suspending state of the application, the Suspending event of the App class is set to the OnSuspending event handler. When the application is in the suspended mode, the event is fired. The SuspendingOperation property is used for accessing the object.

    The GetDeferral property helps application suspension to be delayed. It provides time for the application before the suspension. The Deadline property of the SuspendedOperation defines the maximum time used for defining the object. The information about the remaining time is provided by the property. The SaveAsync method of the SuspensionManager is invoked in the application state.

    private async void OnSuspending(object sender, SuspendingEventArgs e)
        var d1 = e.SuspendingOperation.GetDeferral();
        await SuspensionManager.SaveAsync();
    For storing the navigation information, the frame is to be registered with the SuspensionManager. The OnLaunch method of the Application class is overridden. The Frame object is created and registered with the class. The frame navigation information is saved, the variable is filled and the state can be restored. The RestoreAsync method is used to restore the application which was terminated previously.

    The following code snippet demonstrates the navigation state of the application.

    protected async override void OnLaunched(LaunchActivatedEventArgs e)
        Frame r1 = Window.Current.Content as Frame;
        if ( r1 == null )
            r1 = new Frame();
            r1.Langauge = Windows.Globalization.ApplicationLanguages.Languages[0];
        SuspensionManager.RegisteredFrame ( r1, “app1” );
        if ( e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            await SuspensionManager.RestoreAsync();
        Window.Current.Context = r1;
    if ( r1.Content == null )
        if(!r1.Navigate(typeof(MainPage) e.Arguments) )
            throw new Exception (“Initial page cannot be created”);

    Testing Suspension

    Once you start an application, navigate between several pages, and wait for the application termination. The Task Manager can be used to Suspend the application. Using Debugger, the application is suspended as soon as it reaches the breakpoint. The suspension is disabled when the application is execution in debugger.

    If user navigates the Debug location toolbar, there are three buttons as Suspend, Resume and Shutdown. If the Suspend and Shutdown option is selected, then user executes the application it moves to the previous state of the ApplicationExecutionState.Terminated and opens the page the user opened.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice