plm and background tasks by jason fox

Post on 24-May-2015

328 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Process Lifecycle Managementand Background TasksJason FoxPremier Field EngineerMicrosoft

AgendaSuspend, resume and terminateBackground tasks

You’ll leave understanding:How and when Windows Store Apps run. How to execute code when your app doesn’t run.

When Do Apps Run? WSA System manages app lifetimeDesktop User manages app lifetime

demoTask switching

Process Lifetime Walkthrough

Running

Terminated

SuspendedApp terminated under memory

pressure without notification

App 1 App 2 App 3 App N

Apps suspend after a short delay

Apps resume instantly from

suspend

Introducing Suspend System resources are focused on the app that the user is interacting with in the foreground

Suspended apps have no impact on battery life or responsiveness of the active app

Enables instant switching between apps!

Termination User explicitly closes the app System needs more memory User switch occurs User logoff/System shutdown App crash

Apps do not get notified when they are getting terminated

Registering for Suspend and Resume is Easy

//Register for the Suspending event and call suspendingHandler when receivedWindows.UI.WebUI.WebUIApplication.addEventListener("suspending", suspendingHandler);

//Handle the suspending event and save the current user session using WinJS sessionStatefunction suspendingHandler(eventArgs) { //We are getting suspended } //Register for the Resuming event and call resumingHandler when receivedWindows.UI.WebUI.WebUIApplication.addEventListener("resuming", resumingHandler);

function resumingHandler(eventObject) {

//We are getting resumed, in general do nothing

}

Registering for Suspend and Resume is Easy

// Register for the Suspending event and call OnSuspending when receivedApp.Current.Suspending += OnSuspending;

// Handle the suspending event and save the current user session using WinJS sessionStatevoid async OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e){ var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } // Register for the Resuming event and call OnResuming when received App.Current.Resuming += OnResuming;

void OnResuming( object sender, object e){ // We are getting resumed, in general do nothing}

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

Tips for Making Your App Look and Feel Fresh

Saving/Restoring User Session StateOnly save and restore user session data

Where the user is in an app State of the pages

HTML/JS Use WinJS.Application.sessionState object Property bag that automatically serializes to disk during suspend Reloads property bag from disk on activation Smart about not reloading state if app crashed

XAML (.NET and Cx) SuspensionManager class generated by VS templates does the same keeps track of the navigation state too

Best Practices for Saving and Restoring State

Scenario You should:

User is using your App Save user data incrementally

App switched away from (Suspending)

Save where the user is – what screen they are on, for example

Not running App launched by user (Activated)

Bring the user back and restore their session as if they never left

Suspended App activatedby user (Resuming)

App specific

Process State Transitions

RunningApp

SuspendedApp

suspendingTerminated

App

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 Launche

s App

Splash screen

Splash Screens During Activation System provided Splash

Screen mechanism provides consistent transition to your app

Shown while Windows launches your app

Developer provides color and image in app manifest

Apps need to present a window within 15 seconds of activation or the app will be terminated

Extended Splash Screens

After first run of your app, cache data so next launchcan show content promptly

For apps that need longer toload

1. Have the first view of your app imitate your splash screen

2. On Activated event handler, position yoursplash screen image appropriately

3. Add some progress indicator so the user knows the app is not hanging

Background Tasks

Review: app process lifetime

RunningApp

SuspendedApp

Suspending Terminated

AppLow

MemoryResuming

RunningApp

SuspendedApp

Suspending Terminated

AppLow

MemoryResuming

Background

Task Executes

The app lifecycle with background tasks

Background

Task Executes

Background

Task Executes

Background Task declaration in manifest

demoVisual Studio

System Trigger

Leaving blank: BackgroundTaskHost.exe

WinRT Component

System trigger in manifestMultiple per app

Yourapp.exe

BackgroundTaskHost.exe

MyBackgroundTask

WinRTComponent

Registration and firing

Windows

Create

Re

Register task for Trigger

Call Run()

Register on User LoginExample System Trigger

using Windows.ApplicationModel.Background;

// Specify the triggerIBackgroundTrigger trigger = new SystemTrigger(SystemTriggerType.SessionConnected, false);

Create user login

trigger

// Associate app code with the triggerBackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();taskBuilder.TaskEntryPoint = “MyApp.Background.RegisterForUserLogin";taskBuilder.SetTrigger(trigger);taskBuilder.Name = “OnUserPresent";

Associate trigger with app code

// Register the task for background executionIBackgroundTaskRegistration taskRegistration = taskBuilder.Register();

Register trigger

Background execution on User LoginExampleSystem Trigger

using Windows.ApplicationModel.Background;

namespace MyApp.Background{ public sealed class RegisterForUserLogin: IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { // Your app code } }}

System triggersTrigger Lock

screenDescription

UserPresent X User becomes present (touches screen, keyboard, mouse)

UserAway X User becomes absent or system idle timer expires.

SessionConnected X User logs in.

ControlChannelReset X Control channel is reset

InternetAvailable   Internet becomes available

NetworkStateChange   Change in connection state (cost, network)

ServicingComplete   App update has finished

OnlineIdConnectedStateChange   Microsoft account connected to logon account has changed.LockScreenApplicationAdded   An app has been added to the lock screen

LockScreenApplicationRemoved   An app has been removed from the lock screen

TimeZoneChange   The system time zone has changed

SmsReceived   SMS message received by mobile broadband device.

BackgroundWorkCostChange X the cost of background work changes

User Remains in Control

Resources Are Metered

  CPU resource quota Refresh period

Lock screen app 2 CPU seconds 15 minutes

Non-lock screen app 1 CPU second 2 hours

Background Task Debugging

demoVisual Studio

System Conditions Condition “latches” trigger Prevents trigger from firing, if it can’t function anyway

System Condition Description

InternetAvailable/InternetNotAvailable Availability of Internet connectivity

UserPresent / UserNotPresent Presence of user

SessionConnected / SessionDisconnected

User’s logged-on status

FreeNetworkAvailable Availability of free internet

BackgroundWorkCostNotHigh Only when on AC

Adding a conditionvar t = new SystemTrigger(SystemTriggerType.NetworkStateChange, false); var btb = new BackgroundTaskBuilder() {    TaskEntryPoint = "BGComponent.BTC",    Name = "NetworkState Changed" };

btb.SetTrigger(t);

SystemCondition c = new SystemCondition(SystemConditionType.UserPresent); btb.AddCondition(c);

BackgroundTaskRegistration task = btb.Register();

Yourapp.exe

BackgroundTaskHost.exe

MyBackgroundTask

WinRTComponent

Cancel

Completed

Progress

Communication between app and Task Progress, Completion, Cancellation events

WindowsCancel

demoBackground Task

Mobile PCs that support Connected Standby• Hardware includes low-power

DRAM, busses, and devices

• Always connected to the internet

• App experiences are always fresh and up to date

• Transitions instantly between on and off states (phone-like behavior)

Requires very low idle power to enable

Connected Standby

Connected standby: Always connected

Mobile broadband(e.g. 3G, 4G, LTE,

etc.)

• How does this work in connected standby?

• Nothing special,one model to stay connected.

• Need a hardware slot

Network Connectivity

• Design background tasks to be short lived.

• Implement a Cancel handler. Cancel all outstanding tasks by using CancelationTokenSource

• Use BackgroundTaskHost.exe as the executable for background tasks.

• Use persistent storage to share data between the background task and the app.

• Ensure that the background task class library is referenced in the main project and its output type is winmd.

• Do not display UI other than toast, tiles or badges from a background task.

• Do not rely on user interaction in background tasks.

Background task best practices

Other background processing

Background Audio Playback Apps can play audio in the background Developers must specify background audio in the app manifest

Each audio stream is given a type (communication, media, game)

Only one audio stream type may play at a given time

Upload/Download in the Background Use the BackgroundTransfer API to upload or download data over HTTP in the background

Initiate upload/download from the foreground and it can continue even though your app is suspended

Key points

Longer Battery Life

Always Reachable Apps

Resources• Further reading and documentation

Introduction to Background Tasks http://go.microsoft.com/fwlink/?LinkID=227329&clcid=0x409

• Enabling download and upload capabilities http://msdn.microsoft.com/en-us/library/windows/apps/hh452975.aspx

• Windows SDK Samples Background Transfer download sample Background Task sample

• Sessions [APP-409T] Fundamentals of Metro style apps: how and when your app will run [HW-456T] Understanding Connected Standby [HW-566T] Networking for connected standby [PLAT-785T] Creating connected apps that work on today's networks [APP-396T] Using tiles and notifications

© 2012 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

© 2012 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

top related