plm and background tasks by jason fox

41
Process Lifecycle Management and Background Tasks Jason Fox Premier Field Engineer Microsoft

Upload: nathalie-goh-livorness

Post on 24-May-2015

328 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: PLM and Background Tasks by Jason Fox

Process Lifecycle Managementand Background TasksJason FoxPremier Field EngineerMicrosoft

Page 2: PLM and Background Tasks by Jason Fox

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.

Page 3: PLM and Background Tasks by Jason Fox

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

Page 4: PLM and Background Tasks by Jason Fox

demoTask switching

Page 5: PLM and Background Tasks by Jason Fox

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

Page 6: PLM and Background Tasks by Jason Fox

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!

Page 7: PLM and Background Tasks by Jason Fox

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

Page 8: PLM and Background Tasks by Jason Fox

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

}

Page 9: PLM and Background Tasks by Jason Fox

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}

Page 10: PLM and Background Tasks by Jason Fox

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 11: PLM and Background Tasks by Jason Fox

Tips for Making Your App Look and Feel Fresh

Page 12: PLM and Background Tasks by Jason Fox

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

Page 13: PLM and Background Tasks by Jason Fox

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

Page 14: PLM and Background Tasks by Jason Fox

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

Page 15: PLM and Background Tasks by Jason Fox

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

Page 16: PLM and Background Tasks by Jason Fox

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

Page 17: PLM and Background Tasks by Jason Fox

Background Tasks

Page 18: PLM and Background Tasks by Jason Fox

Review: app process lifetime

RunningApp

SuspendedApp

Suspending Terminated

AppLow

MemoryResuming

Page 19: PLM and Background Tasks by Jason Fox

RunningApp

SuspendedApp

Suspending Terminated

AppLow

MemoryResuming

Background

Task Executes

The app lifecycle with background tasks

Background

Task Executes

Background

Task Executes

Page 20: PLM and Background Tasks by Jason Fox

Background Task declaration in manifest

demoVisual Studio

Page 21: PLM and Background Tasks by Jason Fox

System Trigger

Leaving blank: BackgroundTaskHost.exe

WinRT Component

System trigger in manifestMultiple per app

Page 22: PLM and Background Tasks by Jason Fox

Yourapp.exe

BackgroundTaskHost.exe

MyBackgroundTask

WinRTComponent

Registration and firing

Windows

Create

Re

Register task for Trigger

Call Run()

Page 23: PLM and Background Tasks by Jason Fox

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

Page 24: PLM and Background Tasks by Jason Fox

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 } }}

Page 25: PLM and Background Tasks by Jason Fox

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

Page 26: PLM and Background Tasks by Jason Fox

User Remains in Control

Page 27: PLM and Background Tasks by Jason Fox

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

Page 28: PLM and Background Tasks by Jason Fox

Background Task Debugging

demoVisual Studio

Page 29: PLM and Background Tasks by Jason Fox

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

Page 30: PLM and Background Tasks by Jason Fox

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();

Page 31: PLM and Background Tasks by Jason Fox

Yourapp.exe

BackgroundTaskHost.exe

MyBackgroundTask

WinRTComponent

Cancel

Completed

Progress

Communication between app and Task Progress, Completion, Cancellation events

WindowsCancel

Page 32: PLM and Background Tasks by Jason Fox

demoBackground Task

Page 33: PLM and Background Tasks by Jason Fox

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

Page 34: PLM and Background Tasks by Jason Fox

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

Page 35: PLM and Background Tasks by Jason Fox

• 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

Page 36: PLM and Background Tasks by Jason Fox

Other background processing

Page 37: PLM and Background Tasks by Jason Fox

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

Page 38: PLM and Background Tasks by Jason Fox

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

Page 39: PLM and Background Tasks by Jason Fox

Key points

Longer Battery Life

Always Reachable Apps

Page 40: PLM and Background Tasks by Jason Fox

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

Page 41: PLM and Background Tasks by Jason Fox

© 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