metro apps start, suspend… apps do not get notified when they are getting terminated

153
www.buildwindows.com Windows 8 BUILD Best-Of Christophe Pichaud Microsoft Architect Sogeti France APP – SAC – TOOL

Upload: dean-rady

Post on 14-Jan-2016

230 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows 8 BUILDBest-Of

Christophe PichaudMicrosoft ArchitectSogeti France

APP – SAC – TOOL

Page 2: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Metro AppsStart, Suspend…

Page 3: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Process lifetime walkthrough

App 1 App 2 App 3Running

Suspended

Terminated

… App N

Apps suspend after a short delay

App terminated under memory

pressure without notification

Apps resume instantly from

suspend

Page 4: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Introducing suspend

• System resources focused on app user is interacting with in the foreground

• Inactive apps have no impact on battery life or responsiveness, they are suspended by the OS

• Enables instant switching between apps!

Page 5: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Termination happens

• System needs more memory• User switch occurs• System shutdown• Apps crash

Apps do not get notified when they are getting terminated

Page 6: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Process state transitions

RunningApp

SuspendedApp

suspending TerminatedApp

Low Memory

Code gets to runNo code

runs App not running

resuming

App gets 5s to handle suspend

App is not notified before

termination

Apps are notified when they have been resumed

User Launches App

Splash screen

Page 7: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Suspend under the hood

• Suspended apps are not scheduled by the NT Kernel• No CPU, Disk or Network consumed• All threads are suspended• Apps remain in memory• Kernel ensures apps are not suspended in critical

sections that could cause system wide deadlocks• Apps instantly resumed from suspend when brought

to foreground

Page 8: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

App Activation Through Contracts

• Apps are activated through contracts• Launch, search,

ShareTarget, etc.

• Apps need to initialize contract specific actions

• Context is provided

Running App

launch

shareTarget

activated

kind

search

Page 9: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

App crash? Start over

• Apps that are stuck are no fun• Your app can be terminated abruptly in any of these

cases• Too long to load• Too long to suspend• Stopped handling input messages (Blocking I/O on UI

thread)• Task manager

• Bring the user back home, and ignore saved user session state

• previousExecutionState is provided in activation event args

Page 10: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Use live tiles to appear running

• Your app’s tile is an opportunity to provide value to users even when they are not using your app

• Gives the user the sense that there is something going on with your app, and is an invitation to go back

• Two mechanisms available to update tiles on the Start screen

Page 11: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Lock screen apps

• Apps that can run in the background

• Designed for real-time communications apps (Mail, IM, VoIP)

• Maintain TCP sockets in the background

• Run code periodically• Run code in response to

system events (user login)

Page 12: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Metro Style Apps connected

Page 13: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Review app process lifetime

RunningApp

SuspendedApp

Suspending Terminated

AppLow

MemoryResuming

Page 14: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Network Trigger

RTC trigger APIs for your apps

System Trigger Time Trigger

Background Task Infrastructure

VoIP IM Mail

App OS

Page 15: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Key points

Longer Battery Life

Always Reachable Apps

Page 16: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Recap

Page 17: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

WinRT APIs for Metro style apps

FundamentalsAuthenticat

ionCryptograp

hyGlobalizati

on.NET Win32App

Lifetime

Communications & Data

Contracts XML Web

NetworkingNotification

s

Local & Cloud StorageMedia

Capture

PlayTo

Devices

Sensors

Geolocation Portable

Devices

NFC

User InterfaceHTML5 /

CSSXAML DirectX Controls

Input Accessibility Printing

Data Binding

Tiles

Streams

Background Transfer

SVG

AtomPub

SMS

Printer

Visual Effects

Transcoding

Page 18: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

FundamentalsAuthenticat

ionCryptograp

hyGlobalizati

on.NET Win32App

Lifetime

Communications & Data

Contracts XML Web

NetworkingNotification

s

Local & Cloud StorageMedia

Capture

PlayTo

Devices

Sensors

Geolocation Portable

Devices

NFC

User InterfaceHTML5 /

CSSXAML DirectX Controls

Input Accessibility Printing

Data Binding

Tiles

Streams

Background Transfer

SVG

AtomPub

SMS

Printer

Visual Effects

Transcoding

APIs make it simple to build Metro style apps

Page 19: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

HTTP APIs

Socket APIs

Background APIs

Data APIs

Json XML Streams

DataReader/DataWriter

Cost

Information APIsDownlo

ad

Web services

Skydrive

TCP sockets

UDP sockets

SSL socketsWeb

Sockets

AtomPubRSS

Network Information

Proximity sockets

Live ID

Upload

APIs make it simple to build Metro style apps

Xbox Live Azure

HttpWebRequest

HttpClient

XHR

IXHR

WCFAtom

RTCPush

NotificationCost

Page 20: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Using DirectX in Metro style apps

• App initialization• CoreApplication & CoreWindow

• Handling events• Pointer, gestures, keyboard

• Resource creation• GPU & CPU resources

• Rendering

Page 21: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

What is the Windows Runtime?

Page 22: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows 8

Windows Kernel Services

JavaScript(Chakra)

C/C++ C#, VB

Metro style Apps

Communication

& Data

Application Model

Devices & Printing

Windows Runtime APIs

Graphics & Media

XAML HTML / CSS

HTMLJavaScri

pt

CC++

C#VB

Desktop Apps

Win32

.NET SL

Internet Explore

r

Syst

em

Serv

ices

Vie w

Mod

el

Con

trolle

r

Kern

el

Page 23: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime Architecture

Windows Metadata & Namespace

Language Projection

Windows Core

Windows Runtime Core

XAML Storage …Network

UI Pickers MediaControls

Metro style app

Runtime Broker

Language Support (CLR, WinJS, CRT)

Web Host (HTML, CSS, JavaScript))

Page 24: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Design Principles

• Major improvement to developer experience• Great intellisense & tooling

• Responsive and Fluid• Async APIs where they are needed

• App-Centric Platform• Well managed app-to-app contracts

• Platform based Versioning• Apps keep running on future Windows versions

Page 25: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Metadata

• Concise, complete description of the Windows Runtime

• Generated natively from C++ or C#/VB Compiler

• Efficient binary format derived CLI Metadata• Same structures, different meanings

• Rich enough to allow multi-language projection generation

• Full intellisense on statically known information

Page 26: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

The Windows Namespace

• Windows.* Runtime objects are in a simple, unified, hierarchical namespace

• Great intellisense and browsing in Visual Studio

• One Clear type for each function

• Catalog is extensible but private• Your apps can add objects (in C++/C#)• Objects can be seen from JavaScript

Page 27: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime Basic TypesStrings HSTRING Avoids copying in multiple

languages

Basic Types INT32, UINT64 * Pointers allowed in limited cases

Enumerations enum AsyncStatus Flag or non-flag styles

Structures struct Rect; Can contain strings, but not interfaces

Simple Arrays INT32 [] For very basic collections

Interfaces IInspectable Methods are defined in interfaces

Generic Interfaces

IVector<T> Type-generic interface

Runtime Class Windows.Storage.StorageFile

Binds interfaces to make a class

Page 28: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Shell32.dll

What is a Windows Runtime Object?

Object

IInspectableIUnknown

IStorageItemInformationIStorageItemIStorageFile

Interfaces

FileInformation

Runtime Class

Activation Store (Registry)

Windows Metadata (Disk)

Page 29: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Projections

Object

IInspectableIUnknown

Windows Metadata

C++ App

Pro

jecti

on

CLR

C#/VB App

Pro

jecti

on

HTML AppCh

akra

Pro

jecti

on

Page 30: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Object Creation

Start

App asks to create object

Pass Name to RoActivateIns

tance

Find DLL using Catalog Load DLL

Call DllGet-ActivationFact

ory

Object created by

implementation code

IInspectable returned

Projection creates wrapper (using

metadata)

Object bound to wrapper

Wrapper returned to

App

End

App

Projection

WinRT Object Manager

WinRT Object

Page 31: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Versioning

Object

IInspectableIUnknown

Windows Metadata

v8

App

Pro

jectio

n

Futu

re W

ind

ow

sW

indow

s 8

Object

IInspectableIUnknown

Windows Metadata

v9

App

Pro

jectio

n

Page 32: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime Patterns

Collections IVector<T>, IVectorView<T>, IMap<T>

Iterators, Collections and events cross-language

Delegates delegate AsyncActionCompletedHandler

Encapsulate the context to call back to an object

Events IApplicationLayout::LayoutChanged

Lists of callback recipients

PropertySet interface IPropertySet Collection of items with varying types

Async Interface

ReceivePropertiesOperation A way to get a delayed result without blocking

Contracts Windows.ApplicationModel.DataTransferManager

Connect Apps to Windows Extension Points

Page 33: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Collections

Array

IInspectableIUnknown

IVector<T>

IVectorView<T>

IObservableVector<T>

Associative Collection

IInspectableIUnknown

IMap<T>

IMapView<T>

IObservableMap<T>

C++ AppSTL-style Projection

CLR

C#/VB AppIEnumerable

(T) style Projection

HTML AppCh

akra

JavaScriptProjection

Page 34: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Asynchronous Objects

• Basic requirement for Metro style apps• Always responsive, ready• “Long running” APIs must be delivered as async

• Simpler to allow apps to make synchronous calls• But then bad apps can overwhelm quality of system

• Instead, build async into API shape• And have language projections integrate it deeply

Page 35: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

App

Threading

Windows UI

Object

Main UI Thread

Windows

Object

Threadpool

App Code App Code App Code

Windows

Object

Page 36: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime Threading

• Three main types of object• Thread bound – works only on the thread where it was

created – most UI• Thread flexible – works on any thread, uses locking if

needed to control simultaneous access• Brokered – out of process

• UI runs in single threaded environment that is not reentrant (“ Application STA”) • Callbacks can only enter if they are related to an

outgoing call• Most non-UI runs in any thread

Page 37: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

RuntimeBroker.exe

Brokered Objects

Windows Runtime Object

IInspectable

IUnknown

App

Pro

jecti

on

Pro

xy

Page 38: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Inside WinRT

Page 39: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

The Windows Runtime is fundamental to Metro style apps.

Page 40: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

WinRT registration catalogs Install

Launch Contract

Extension 1

Extension 2

Runtime Class “A”

Class CatalogExtension Catalog

Search Contract

Extension 3

Runtime Class “B”

Runtime Class “C”

Page 41: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

WinRT registration Install

Extension Registrations

• Several OS supported contracts

• Extensions are contract implementation

• Extensions map the abstract to the concrete

Class Registrations

• Classes are concrete implementations

• Contains information to activate and run code

Page 42: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Deployment pipeline Install

Class Catalog

Extension Catalog

Deployment Engine

<Applications> <Application Id="App" StartPage="default.html"> <VisualElements DisplayName="Hello World" Logo="images\logo.png" Description="Hello_World" ....

Application Manifest

Page 43: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Tapping a tile

• The OS stores the extension’s identification during install

• The OS queries the extension catalog to find the extension

• The OS activates the extension via WinRT

Tap

Page 44: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Finding the right extension Tap

Class Catalog

Extension Catalog

Explorer.exe

Activation

System

Query

InvestigateActivate

ExtensionCatalog

ExtensionRegistration

Page 45: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Activating the extension Tap

Class Catalog

Explorer.exe

Activation

System

ActivateExtension

Registration

RPCSS

DCOM Launch

Application.exe

Page 46: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Running the app Run

Application.exe

RPCSS

Class Catalog

main(){ ...}

Core Application

Object

Run

Register

Query

MTA

Page 47: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Completing app activation Run

Application.exe

App Code Core Application

Object

RPCSS

Explorer.exe

Activation

SystemExtension

Registration

Instance

InstanceComplete Activation

ActivateApp

AppCallback

Page 48: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Application object Run

Application.exe

Private Interfaces

ICoreApplication

CoreApplication

ICoreApplicationExit

PLM Integration

Activation RouterICoreApplicationInitialization

Application Code

MTA STA #1

Application Code

STA #2

Application Code

Run

Register

ActivateRun

Page 49: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

WinRT APIs Foundations

Page 50: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

50

Windows Runtime APIs

Windows Runtime

JavaScript

C#/VBC++

Available to all programming languages

Requires a language neutral type system

Page 51: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Numeric types

• Behave differently in .NET/C++ compared to JavaScript• C++/.NET - Signed, Unsigned; 8, 16, 32, 64 bit int; 32, 64

bit float• JavaScript – double-precision 64-bit binary format IEEE

754 value• Windows Runtime – Same as C++/.NET without signed 8-

bit integer• But…

• Operating system uses 64-bit integers in some places• file sizes, position, etc.

• JavaScript number can only represent 53 bits of precision

Page 52: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Numeric types

• ECMAScript (ECMA-262) Standard• Requires numbers treated as IEEE-754 64-bit floating

point values• JavaScript applications using the Chakra runtime cannot

accurately determine the values of some 64-bit integers• But such values can be received from and passed back to WinRT

APIs• Many (most) values will work fine

• Use caution with 64 bit values whose absolute value is greater than 2^53 (9,007,199,254,740,992)

Page 53: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Strings

• Immutable or mutable?• Immutable – JavaScript, .NET; Mutable – C++

• Null• JavaScript: null is an object, string is a type• C++: std::string has no 'null' semantics• .NET System.String: reference type has a 'null'

distinguished value• Windows Runtime: string's immutable, no null

representation

Page 54: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Structures

• Handled differently by languages• C++/CLR: Structures are value types, can contain all

types• JavaScript: Has no structure construct but structures can

be simulated• Windows Runtime supports structures, with restrictions

on content• Can only contain numbers, strings or structures

• Windows Runtime structures cannot contain pointers• Windows Runtime structures are value types

• As a result…• Structure valued property behavior differs in languages

Page 55: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

• Target languages handle pointers and references differently• C++: All types can be passed by value or by reference• .NET: Objects are passed by reference, value types by

value• JavaScript: Objects passed by reference, numbers passed

by value• Windows Runtime: Objects (Interfaces) passed by

reference, all other types passed by value

• As a result…• Method parameters are [in] or [out], never [in, out]

References & pointers

Page 56: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Arrays

• Reference or value types?• JavaScript, .NET, C++: Reference types

• Windows Runtime• Arrays are value types so marshal by value

• ONLY WHEN they are marshaled!

Page 57: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Events

• Event syntax differs across languages• C++/CLR – Clients add events with += operator• JavaScript – Clients add events with either the

addEventListener function or by setting the “on<eventname>” property on the object.

• Be aware…• JavaScript event name casing is all lowercase• Assigning to the property implies one listener while

addEventListener allows multiple listeners• Misspelling the event name in either case silently fails

Page 58: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Collections

• Windows Runtime collections are relatively straightforward• Vectors – similar to array, projected with array syntax• Maps – key/value pairs, projected as dictionary to CLR

apps

• Surprise…• Because collection value accesses require a method call,

they can be unexpected performance bottlenecks• Can use the GetMany method for bulk retrieval

Page 59: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Method overloading

• Two criteria used when handling overloads• Overload on number of params (arity)

• JavaScript, .NET, C++ all distinguish methods by arity• Overload on parameter type

• .NET, C++ all distinguish methods by type of parameters• JavaScript has a limited notion of type

• Windows Runtime methods• Overload on arity but not on type

Page 60: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Asynchronous APIs

• Platform design goal that APIs cannot block the UI thread• Guidance: Anything taking > 50 ms should be

asynchronous• Resulted in prevalent use of Async Pattern in platform

• Established a naming pattern: <verb>[<noun>]Async• GetThumbnailAsync

• Return value mapped to a promise for a future result• In .NET – await obj.GetThumbnailAsync()• In JavaScript – obj.GetThumbNailAsync().then (func);

Page 61: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

.NET parallel programming

Page 62: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

TPL DataflowOverview

• System.Threading.Tasks.Dataflow.dll

• Primitives for in-process message passing• “Blocks” that can buffer and process data• Used individually and/or linked together to create networks

• Inspired by• Decades of computer science research/history• Related Microsoft technologies

• Asynchronous Agents Library in Visual C++ 2010• Axum incubation project• CCR from Microsoft Robotics

Page 63: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

• “Dataflow Blocks” implement interfaces• IDataflowBlock, ITargetBlock<TInput>,

ISourceBlock<TOutput> • Linkable to form a network

• Data automatically propagated from sources to linked targets

• Enables building powerful parallel and asynchronous pipelines, e.g.

• ActionBlock, TransformBlock, JoinBlock, …• Integrates with Task, IObservable, …

TPL DataflowDataflow Networks

TransformBlock<byte[],byte[]>

Compress

TransformBlock<byte[],byte[]>

Encryptcompress

eddata

and encrypted

Page 64: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Parallel Debugging Additions

• Parallel Watch

• Multi-process

• Pervasive Flagging

Page 65: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Concurrency Visualizer

• Shift-Alt-F5

• Faster processing, faster loading• Supports big traces

• Supports EventSource and custom markers• Built-in support for TPL, PLINQ, Sync Data Structures, and

Dataflow• Built-in support for your own EventSource types

• Also provides Visual Studio markers API

• New visualizations• e.g. defender view

Page 66: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

C++ and XAML

Page 67: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

XAML benefits

• For WPF, SL and Windows Phone developers• Utilize current skills• Reuse compatible assets

• For those new to XAML• Powerful declarative programming model• Separation of UI layer and application logic• Expressive: Controls, layout, vector drawing• Comprehensive : Styles, templates, data binding, animation• Extensible : Custom controls

Page 68: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

C++ for the Windows 8 runtime

• Set of language extensions and libraries to allow direct consumption and authoring of Windows runtime types.

• Strongly-typed system for Windows runtime• Automatically reference counted• Exception-based• Deep integration with STL• Well defined binary contract across module boundaries

Page 69: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

C++: First class support for Metro style apps• XAML designer• C++ to access the Windows runtime• Async nature of APIs• IDE improvements• Local, simulator and remote debugging• Package your apps• Code Analysis

Page 70: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Using Windows Runtime from C#

Page 71: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

C# and Visual Basic influencedthe Windows Runtime

Page 72: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime is designed to be used from object-oriented

languages like C# and Visual Basic

Page 73: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime metadata files use an updated version of .NET’s

metadata format

Page 74: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime includes a XAML based framework for Metro style

apps

Page 75: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows Runtime was expressly designed

to work well with C# and Visual Basic

Page 76: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Most differences between Windows Runtime and

.NET are hidden from the managed developer

Page 77: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

IIterable<T> ↔ IEnumerable<T>

IVector<T> ↔ IList<T>

IVectorView<T> ↔ IReadOnlyList<T>

IMap<K,V> ↔ IDictionary<K,V>

IMapView<K,V> ↔ IReadOnlyDictionary<K,V>

.NET automatically maps collection interfaces to their Windows

Runtime equivalent

Page 78: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

A few places use extension methods to bridge between Windows Runtime and managed code

Page 79: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

You can write your own Windows Runtime components

in C# or Visual Basic

Page 80: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

You should build a Windows Runtime component when you want

your code to be used fromJS, C++, C# and VB

Page 81: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

API signatures must only use Windows Runtime types

Inheritance can only be used for XAML controls,

all other types must be sealedOnly supports system provided generic types

Structs can only have public data fields

Page 82: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Influenced by C# and VB

Feels natural and familiar from C# and Visual Basic

Build your own managed Windows Runtime components

Page 83: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Using Windows Runtime with C++

Page 84: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

C++ in a Metro style WorldOverview

• Metro style Applications (Hybrid)• HTML5 + JS front-end• C++ components

• XAML UI Applications• XAML interface• C++ code behind

• Metro style Games• DirectX & C++

Page 85: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

C++ for Windows RuntimeOverview

• Set of language extensions and libraries to allow direct consumption and authoring of Windows Runtime types.

• Strongly-typed system for Windows Runtime• Automatically reference counted• Exception-based• Deep integration with STL• Well defined binary contract across module boundaries

Page 86: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Key Bindings Feature Summary

1. Data Types ref class Reference type

value class Value type

interface class Interface

property Property with get/set

event “Delegate property” with add/remove/raise

delegate Type-safe function pointer

generic Type-safe generics

2. Allocation gcnew Garbage-collected allocation

ref new Reference-counted allocation

3. Pointer & Reference

^ Strong pointer (“hat” or “handle”)

% Strong reference

BINDINGS TO FOREIGN TYPE SYSTEMSC++ Component Extensions (C++/CX)

Page 87: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

WinRT Types: For Cross-Language Use

ModuleInternals

written in C++

WinRT External Surface

for WinRT callers/callees

C/C++ External Surface

for native callers/callees

Page 88: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Lifetime Management

• Handle (^) is a pointer to a Windows Runtime object for which the compiler performs automatic reference counting

• ref new instantiates or activates a Windows Runtime class.

Person^ p;{ Person^ p2 = ref new Person(); // refcount = 1 p2->Name = “John”; // refcount = 1 p = p2; // refcount = 2} // refcount = 1p = nullptr; // refcount = 0; ~Person()

Page 89: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Runtime Class

• Definingpublic ref class Person { public: Person(String^ name, String^ email); void Greet(Person^ other); internal: ~Person(); void SetPassword(const std::wstring& passwd);};

• ABI-safe cross-language class• Public methods restricted to WinRT typed parameters• Private/internal methods can use any legal C++ type parameters

• UsingPerson^ p = ref new Person(“John Surname”);p->Greet(ref new Person(“Jim Surename”);

Page 90: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Interface

• Definingpublic interface class IAnimal { void Play();};

• Methods are implicitly public

• UsingIAnimal^ animal = ref new Cat();animal->Play();

• Inheritingpublic interface class IFeline : IAnimal { void Scratch();};

• Implementingref class Cat : IFeline { public: virtual void Play(); virtual void Scratch();};

• Public inheritance only

Page 91: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Automatic Lifetime (Stack, Member)

• Definingpublic ref class DatabaseConnection { public: ~ DatabaseConnection();};

• Using{ DatabaseConnection db(); db.SetName( “Employees”); // … // … lots of queries, updates, etc. … // …} // ~DatabaseConnection()

Page 92: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Property

• Defining• Trivial properties (with private backing store)

public: property String^ Name;• User defined properties

public: property Person^ Sibling { Person^ get() { InitSiblings(); return _sibling; }

void set(Person^ value) { _sibling = value; NotifySibling(); } }private: Person^ _sibling;

• UsingPerson^ p = ref new Person(“John”);p->Sibling = ref new Person(p->Name);

Page 93: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Delegate

• Declaring: like a functionpublic delegate void PropertyChanged( String^ propName, String^ propValue );

• Instantiating: like a class• From lambda:

auto p = ref new PropertyChanged( [](String^ pn, String^ pv) { cout << pn << ” = “ << pv; } );

• From free-function

auto p = ref new PropertyChanged( UIPropertyChanged );• From class-member

auto p = ref new PropertyChanged( this, MainPage::OnPropertyChanged );

• Invoking: like a functionp( “Visible”, false );

Page 94: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Event• Defining

• Trivial event (with private backing store)public: event PropertyChanged^ OnPropertyChanged;

• User defined eventpublic: event PropertyChanged^ OnNetworkChanged { EventRegistrationToken add(PropertyChanged^); void remove(EventRegistrationToken t); void raise(String^, String^);}

• Using• Subscribing

person->OnPropertyChanged += propertyChangedDelegate;auto token = person->OnPropertyChanged::add(propertyChangedDelegate);

• Unsubscribingperson->OnPropertyChanged -= token;person->OnPropertyChanged::remove(token);

Page 95: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Exception

• Signaling an error case: throw exception• throw ref new InvalidArgumentException();• throw ref new COMException(E_*);

• Handling an error case: catch exception• try { … } catch (OutOfMemoryException^ ex) { … }• Access HRESULT value via ex->HResult

• Notes on exceptions:• catch (Platform::Exception^) catches all WinRT exceptions• Exceptions don’t carry any state and don’t travel across modules• Deriving from an exception class is ill-formed

HRESULT Exception

E_OUTOFMEMORY OutOfMemoryException

E_INVALIDARG InvalidArgumentException

E_NOINTERFACE InvalidCastException

E_POINTER NullReferenceException

E_NOTIMPL NotImplementedException

E_ACCESSDENIED AccessDeniedException

E_FAIL FailureException

E_BOUNDS OutOfBoundsException

E_CHANGED_STATE ChangedStateException

REGDB_E_CLASSNOTREG

ClassNotRegisteredException

E_DISCONNECTED DisconnectedException

E_ABORT OperationCanceledException

Page 96: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Generics

• Defininggeneric<typename T, typename U> public interface class IPair {

property T First;property U Second;

};

• UsingIPair<String^, Uri^>^ uri = GetUri();auto first = uri->First; // type is String^auto second = uri->Second; // type is Uri^

• Implementingref class PairStringUri: IPair<String^, Uri^> {public:

property String^ First;property Uri^ Second;

};

Page 97: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Template Runtime Class

• Definingtemplate<typename T, typename U>ref class Pair: IPair<T, U>{public:

property T First;property U Second;

Pair(T first, U second) { First = first; Second = second; }};

• UsingIPair<String^, Uri^>^ pair = ref new Pair<String^, Uri^>( “//BUILD/”, ref new Uri(“http://www.buildwindows.com”));

Page 98: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

.winmd metadata

• .winmd files • Contain the metadata representation of WinRT types

• To consume a winmd file:• Right click on project in Solution Explorer > References > Add New Reference…

Or

• #using <Company.Component.winmd>• Make sure the winmd and implementation dll is packaged together with your

application

• To produce a .winmd file:• Start from the “C++ WinRT Component Dll” template• Define public types (ref classes, interfaces, delegates, etc.)

Tip: C++ WinRT components can be consumed from C++, JS or C#

Page 99: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Partial Runtime Class

• Partial class definitionprivate partial ref class MainPage: UserControl, IComponentConnector{public: void InitializeComponent(); void Connect() { btn1->Click += ref new EventHandler(this, &MainPage::Button_Click); }};

• Class definitionref class MainPage{public: MainPage() { InitializeComponent(); } void Button_Click(Object^ sender, RoutedEventArgs^ e);};

Page 100: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Libraries

Page 101: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Vector and ObservableVector• Instantiating

using namespace Platform;Vector<String^>^ items = ref new Vector<String^>();

• Adding elementsitems->Append(“Hello”);

• Returning a read-only view of the vectorIVectorView<String^>^ GetItems () { return items->GetView();}

• Getting notification for changesitems->VectorChanged += ref new VectorChangedEventHandler<String^> (this, &MyClass::VectorChanged);

Page 102: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Map and ObservableMap

• Definingusing namespace Platform;Map<String^, Uri^> favorites = ref new Map<String^, Uri^>();

• Adding elementsfavorites->Insert(“MSDN”, ref new Uri(“http://msdn.com”));

• Checking and removing elementsif (favorites->HasKey(“MSDN”)) favorites->Remove(“MSDN”);

Page 103: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Library Integration: STL

• STL Algorithms• String has Begin()/End()

member methods.• For WinRT collections,

collection.h defines begin() and end() functions.

IVector<int>^ v = GetItems();int sum = 0;std::for_each( begin(v), end(v), [&sum](int element) { sum += element; } );

• Conversions• String^ std::wstring (via

wchar_t*)• Vector std::vector

std::vector<int> v;v.push_back(10);auto items = ref new Vector<int>(v);• Vector std::vector

Vector<int>^ items = …;std::vector<int> v = to_vector(items);• Map std::map

Page 104: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

WinRT and JavaScript Basics

Page 105: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

JavaScript and C# WinRT component// C#namespace CustomWinRTComponent { public interface IMoreMath { } public sealed class MoreMath : IMoreMath { public static double Sinh(double x) { return Math.Sinh(x); } }}

// JavaScriptvar MoreMath = CustomWinRTComponent.MoreMath;var y = MoreMath.sinh(0.7);

Page 106: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

C++ and Metro Style Apps

Page 107: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

• Read / write metadata

• Maps between C++ patterns (e.g. constructors) and WinRT interfaces

• Maps between output parameters and return values

• Automatic reference counting

• Casting

• Maps between exceptions and HRESULTs

The C++ language extensions

Page 108: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Exception & return value wrapping

try { int i = Add(41, 1);} catch (OverflowException^ e) { printf("Too big"); }

inline int Add(int i, int j) { int res; HRESULT hr = __cli_Add(this, i, j, &res); if (hr != 0) { __throw_hr_as_exception(hr); // switch on hr & throw } return res;};

int Add(int i, int j) { if (i+j < i) { throw OverflowException(); } return i + j;}

HRESULT __stdcall Add( Calculator* this, int i, int j, int* result )

HRESULT __stdcall __cli_Add(Calculator* calc, int i, int j, int* r) { try { *r = calc->Add(i, j); } catch (Exception^ e) { return e->HResult; } return S_OK;};

WinRTABI

Native to COM Wrapper COM to Native Wrapper

Page 109: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

H^T

• A hat is a pointer to a pointer to an array of function pointers• aka: Pointer to vptr to vtable

“It’s not okay to call me a carrot”

Calculator::ICalculator vtable

&Calculator::QueryInterface

&Calculator::AddRef

&Calculator::Release

&Calculator::GetIids

&Calculator::GetRuntimeClassName

&Calculator::GetTrustLevel

&Calculator::Add

ref class Calculator

IStorageCell vtable * vfptr1

ICalculator vtable * vfptr2

int _storage

int _refcount

ICalculator^ calc

Page 110: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

H^T

• A hat is a pointer to a pointer to an array of function pointers• aka: Pointer to vptr to vtable

• ^ provides automatic reference counting• Similar to ComPtr<T>• Adds ability to use casting.

“It’s not okay to call me a carrot”

Page 111: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

C++ for Metro style apps

• C++ language extensions gives you the best of both C++ and WinRT

• The compiler understands the concepts natively, and will do the best job at optimizing

• While giving you a readable and natural syntax

• C++ and Win8: power and performance!

Page 112: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Brings existing C++ code into Metro Style Apps

Page 113: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows SDK for Metro style apps

Windows Core OS Services

JavaScript(Chakra)

CC++

C#VB

Metro style apps

Communication

& Data

Application Model

Devices & Printing

WinRT APIsGraphics &

Media

XAML HTML / CSS

HTMLJavaScri

pt

CC++

C#VB

Desktop apps

Win32

.NET / SL

Internet Explore

r

Syst

em

Serv

ices

Vie w

Mod

el

Con

trolle

r

Cor

e

Page 114: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows SDK for Metro style apps

• Windows 8 introduces the concept of “app container” broker• Access to a number of resources (files, devices,

etc.) is controlled by the broker• A large number for Win32 APIs are replaced by

the WinRT library• A good number of Win32 APIs will not be available

• E.g. GDI, Registry, MessageBox, etc.• http://go.microsoft.com/fwlink/?LinkId=228532

Page 115: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Existing code

Standard C++ Libs

ppl (parallel patterns lib)

Win32

ATL

MFC

3rd party libs (boost, etc.)

your code

Desktop apps

good

good

WinRT + Win32 subset

ATL subset

no

depends

depends

Metro style apps

Mic

roso

ft L

ibra

ries

Page 116: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Existing 3rd party libraries

• 3rd party Libraries will need to review their usage of existing Win32 APIs

• A few examples:• boost: low usage of APIs not part of Windows SDK

for Metro style apps• Physics engines (e.g. Bullet): the core of the

library have small usage of non-Metro style SDK APIs

• Math libraries (e.g. Deal.II, SciMath, etc.): very little usage (if any) of non-Metro style SDK APIs

Page 117: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Your code

Basic steps to migrate your code to the Metro style environment

• Make sure you remove or replace the usage of non-Metro style SDK APIs• Flagged by compiler errors

#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)

• Flagged by Logo Verification Toolkit

• (if needed) Add a WinRT layer for smooth interoperability with any Metro style app

Page 118: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Metro style SDK partitioning

// c:\Program Files (x86)\Windows Kits\8.0\Include\um\mmdeviceapi.h

#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)

// Metro style SDK APIs

#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) */

#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)

// Desktop SDK APIs, not available for Metro style apps

#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */

Page 119: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

.NET Kernel

Page 120: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Quick Reminder – What Is The CLR

Base Class Libraries The CLRJIT & NGEN

Garbage Collector

Security Model

Exception Handling

Loader & Binder

Profiling& Debugging APIs

Entity Frame-work

ASP. NET

WCFAnd

more!WorkFlow

WPFWin

Forms

Page 121: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Improvements to the Garbage Collector

Page 122: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Generation 1 Generation 0

• New objects allocated as Generation 0• Accessible References Keep Objects Alive • GC Compacts Referenced Objects• Objects Promoted to Older Generation

Quick Reminder – GC Fundamentals

Roots

Heap

Page 123: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Quick Reminder – GC Fundamentals

• 2 Modes: Client (default) and Server

• Heaps

• Collection Flavors

Small Object Heap Large Object Heap

Client GC One One

Server GC One per logical processor

One per logical processor

Gen0/Gen1 Gen2

Client GC Always blocking Can be non-blocking

Server GC Always blocking Can be non-blocking

Page 124: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Quick Reminder - Server Mode (4.0)

• (.NET 4.0) Maximizes application scalability

Page 125: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Background GC For Server Mode (New in 4.5)Performance: Reduces pause times (Desktop apps)

• (.NET 4.5) Gen0/Gen1 collections can proceed during Gen2 GC

Page 126: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Other GC ImprovementsPerformance

• (Server GC) Scalable Marking for full blocking GCs

• Large Object Heap Allocation Improvements• Better use of free space on LOH • (Server only) Balancing the LOH allocations across

processors

• … And More!

http://blogs.msdn.com/b/clrteam/ “Enhancements to the CLR GC in .NET 4.5”

LEARN MORE

Page 127: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

App Execute

Automatic NGen model

App Execute

Auto NgenMaintenance

Task

Native Image Cache

Assembly Image

Usage Logs

App Execute(MyApp.exe)

MyApp.exeMyApp.ni.exe

OtherApp.ni.exe

Page 128: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Automatic NGen

• Windows 8 only• .NET 3.5 – Framework Only• .NET 4.5

• Desktop app – Only assemblies in the GAC• Metro style app – All assemblies eligible

Page 129: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Multi-Core Background JITPerformance: Improves startup time (Desktop apps)

FirstLaunch

Subsequent

Launch

Executed Methods Profile

Page 130: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

C# Next

Page 131: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

C# and VB evolution

Managed Code

Generics

Language Integrated Query

Dynamic + Language Parity

C# 5.0 + VB 11.0Windows Runtime + Asynchrony

C# 1.0 + VB 7.0

C# 2.0 + VB 8.0

C# 3.0 + VB 9.0

C# 4.0 + VB 10.0

Page 132: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

What’s new?

C# 5.0

• Windows Runtime support• Asynchronous programming• Caller info attributes

VB 11.0

• Windows Runtime support• Asynchronous programming• Caller info attributes• Iterators

Page 133: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Asynchronous programming models

• Windows Runtime: IAsyncOperation<T>• .NET Framework: Task<T>• Javascript: Promises• All are objects representing “ongoing operations”• All use callbacks to signal completion of operation• Challenge: Callbacks turn your code inside out• Insight: Automatic transformation to callbacks is

possible

Page 134: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Class

Field

public Foo

private

string

X

The Roslyn project

CompilerCompilerSource codeSource code

SourceFile

Source codeSource code

.NET Assembly

Meta-programming Read-Eval-Print Loop

LanguageObject Model

DSL Embedding

Page 135: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Roslyn APIs

Language Service

Compiler APIs

Compiler Pipeline Syntax Tree API

Symbol APIBinding and Flow

Analysis APIsEmit API

Form

atte

r

Colo

rizer

Ou

tlinin

g

Navig

ate

To

Ob

ject

Bro

wse

r

Com

ple

tion

List

Find

All

Refe

ren

ces

Ren

am

e

Qu

ick Info

Sig

natu

re

Help

Extra

ct M

eth

od

Go To

D

efin

ition

Ed

it an

d

Con

tinu

e

ParserMetadata

Import

Binder IL Emitter

Symbols

Page 136: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Quick Recap• WinRT• Visual C++ Component

Extensions

Page 137: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows 8 APIs

Metro style app

WinRT

Win32(Metro style Subset)

Win32(Desktop Subset)

Windows Core OS Services

Page 138: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Exception^

• WinRT APIs throw exceptions deriving from Platform::Exception

• … really, it’s HRESULTs under the coverHRESULT Exception

E_OUTOFMEMORY OutOfMemoryExceptionE_INVALIDARG InvalidArgumentExceptionE_NOINTERFACE InvalidCastExceptionE_POINTER NullReferenceExceptionE_NOTIMPL NotImplementedExceptionE_ACCESSDENIED AccessDeniedExceptionE_FAIL FailureExceptionE_BOUNDS OutOfBoundsExceptionE_CHANGED_STATE ChangedStateExceptionREGDB_E_CLASSNOTREG ClassNotRegisteredExceptionE_DISCONNECTED DisconnectedExceptionE_ABORT OperationCanceledException

Page 139: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Collections

Page 140: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

WinRT collections family

Vector Map

VectorView

see <collection.h>

MapView

IVector

IVectorView

IObservableVector

IMap

IMapView

IObservableMapIIterable

IIterator

• STL containers are the backing store

Page 141: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Collections usage considerations

1. Mix STL containers with WinRT collections• STL containers are faster but don’t have observable

behavior• Use STL containers internally; use WinRT collections at

the boundary• Fire up a profiler where it matters!

2. Use STL algorithms on WinRT collections• No need to copy the WinRT collection into an STL

container3. You can have STL containers of ^ types4. Use Vector not IVector most of the time

• Only use IVector the public API surface

Page 142: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Collections usage considerations (cont.)

5. VectorView, MapView and Iterator get invalidated• Copy if you plan to change the underlying Vector or Map

6. Each iteration over collections is a virtual call• Use bulk iteration (GetMany) when it makes sense

7. Implementing IVector is tricky• Use an underlying Vector

Page 143: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Async pattern

Page 144: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Async simplified

• Build on Parallel Patterns Library (PPL) tasks to implement async pattern

• Sample available here:http://go.microsoft.com/fwlink/?LinkId=228286

• Using this technique, async code is cleaner and more maintainable

Page 145: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Win32

Page 146: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

Windows SDK for Metro style apps

• Windows 8 introduces the concept of “app container” sandbox• Access to a number of resources (files, devices, etc.) is

controlled by the sandbox• A large number for Win32 APIs are replaced by the WinRT

library• A good number of Win32 will not be available to Metro

style apps

• Some Win32 APIs are still available directly to Metro style apps

• COM Core• Kernel• Accessibility• Audio

• Direct2D• Direct3D• DirectComposition• DirectManipulation• DirectWrite

• File Systems• Globalization• Media Foundation• Windows and

Messages

Page 147: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

C++ renaissance

Page 148: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

C++ Renaissance

• Industry momentum for C++.• Renewing our commitment to C++:

• New programming model for Windows 8.• Get the full power of your CPU and GPU.• Use Windows 8 hardware capabilities to the fullest.• Build for ARM.

Visual C++: The power and performance tool for Windows.

Page 149: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

Recap

Page 150: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

For more information

• PLAT-874T - Lap around the Windows Runtime

• APP-409T Fundamentals of Metro style apps: how and when your app will run

• TOOL-531T Using the Windows Runtime from C# and Visual Basic

• TOOL-532T Using the Windows Runtime from C++

• TOOL-533T Using the Windows Runtime from JavaScript

Related sessions• C++ Language extension s

ummary• The Windows Runtime• Windows Runtime Design

Documentation & articles

Page 151: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

www.buildwindows.com

• Feedback and questions Team Park Windows 8 Dev Community

thank you

Page 152: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated

© 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to

be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Page 153: Metro Apps Start, Suspend… Apps do not get notified when they are getting terminated