SlideShare una empresa de Scribd logo
1 de 26
Oliver Scheer
Senior Technical Evangelist
Microsoft Deutschland
http://the-oliver.com
Async and Await
Programming on Windows
Phone 8
await
async
Agenda
3/17/2014Microsoft confidential2
async and await in C#5 Task Programming Model
How awaitable objects work
The new way to do parallel processing
Replacing BackgroundWorker with async
Learn why you’ll never use Thread or Threadpool again!
• Windows Phone 7.1 Base Class Libraries used .NET 4.0 patterns to support asynchronous
programming
• Async programming model: BeginXYZ, EndXYZ methods
• Example: HttpWebRequest BeginGetResponse and EndGetResponse methods
• Event async pattern: Setup a Completed event handler, then call XYZAsync() to start operation
• Example: WebClient DownloadStringAsync method and DownloadStringCompleted event
• Windows Phone 8 includes many WinRT APIs
• Any API that potentially takes more than 50ms to complete is exposed as an asynchronous
method using a new pattern: Task Programming Model
• Asynchronous programming is a first class citizen of WinRT, used for File I/O, Networking etc
• Task-based programming is becoming the way to write asynchronous code
• Many new APIs in Windows Phone 8 now and in the future will offer only a Task-based API
Async Methods and Task Programming Model
3/17/2014Microsoft confidential3
Keeping UI Fast and Fluid
Comparing blocking File I/O using WP7.1 with TPM File I/O in WP8
3/17/2014Microsoft confidential4
TIME UI Thread
var isf = IsolatedStorageFile.GetUserStoreForApplication();
using (var fs = new IsolatedStorageFileStream(
"CaptainsLog.store", FileMode.Open, isf))
{
StreamReader reader = new StreamReader(fs);
theData = reader.ReadToEnd();
reader.Close();
};
StorageFile storageFile = await
Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appdata:///local/CaptainsLog.store "));
Stream readStream = await StorageFile.OpenStreamForReadAsync();
using (StreamReader reader = new StreamReader(readStream))
{
theData = await reader.ReadToEndAsync();
}
Keeping UI Fast and Fluid
Comparing blocking File I/O using WP7.1 with TPM File I/O in WP8
3/17/2014Microsoft confidential5
TIME UI Thread
Making Asynchronous Code Look Synchronous
3/17/2014Microsoft confidential6
private async Task<string> LoadFromLocalFolderAsync()
{
StorageFile storageFile = await
Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appdata:///local/CaptainsLog.store "));
Stream readStream = await storageFile.OpenStreamForReadAsync();
using (StreamReader reader = new StreamReader(readStream))
{
theData = await reader.ReadToEndAsync();
}
}
Original
Context ThreadpoolTIME
Simpler for Developers to Write Asynchronous Code
3/17/2014
Microsoft confidential7
private async void SomeMethod()
{
…
string theData = await LoadFromLocalFolderAsync();
TextBox1.Text = theData;
…
}
private async Task<string> LoadFromLocalFolderAsync()
{
...
}
All Async methods must
return void, Task or
Task<TResult>
Caller can use the await
keyword to pause until the
async operation has
completed execution on a
Threadpool thread
It automatically marshals
back to the originating
context, so no need to
use the Dispatcher to set
UI objects on the UI
thread
All methods that contain
calls to awaitables must
be declared using the
async keyword
When the async code
completes , it ‘calls back’
and resumes where it left
off, passing back the
return value
• Marking a method with the async keyword causes the C# or Visual Basic compiler to
rewrite the method’s implementation using a state machine
• Using this state machine the compiler can insert points into the method at which the
method can suspend and resume its execution without blocking a thread
• These points are inserted only where you explicitly use the await keyword
• When you await an asynchronous operation that’s not yet completed:
• Compiler packages up all the current state of the calling method and preserves it on the heap
• Function returns to the caller, allowing the thread on which it was running to do other work
• When the awaited operation later completes, the method’s execution resumes using the
preserved state
Compiler Transformations
3/17/2014Microsoft confidential8
private async void SomeMethod()
{
string theData = await LoadFromLocalFolderAsync();
TextBox1.Text = theData;
}
Freeing Up the Calling Thread
3/17/2014Microsoft confidential9
private async void SomeMethod()
{
await LoadFromLocalFolderAsync();
[Preserve state on heap]
}
[Calling thread free to do other work]
Freeing Up the Calling Thread
3/17/2014Microsoft confidential10
[Calling thread free to do other work]
[Calling thread free to do other work]
[Calling thread free to do other work]
{
[Restore Context]
string theData = [Result from LoadFromLocalFolder()]
TextBox1.Text = theData;
}
private async void SomeMethod()
{
await LoadFromLocalFolder();
[Preserve state on heap]
}
[Calling thread free to do other work]
Freeing Up the Calling Thread
3/17/2014Microsoft confidential11
[Calling thread free to do other work]
[Calling thread free to do other work]
[Calling thread free to do other work]
• Error Handling is simpler
• Just use try…catch around the async code, same as with synchronous code
• Exceptions thrown while code is executing asynchronously are surfaced back on the calling thread
private async void SomeMethod()
{
try
{
string theData = await LoadFromLocalFolder();
TextBox1.Text = theData;
}
catch (Exception ex)
{
// An exception occurred from the async operation
}
}
Error Handling
3/17/2014Microsoft confidential12
• No, you can call async methods without await
• Called method still executes on background thread
• The calling thread does not wait for the result
• Only feasible for async methods that return void or Task, not Task<TResult>
• Intellisense warns you when you do this
Must I use await with async methods?
3/17/2014Microsoft confidential13
Replacing
BackgroundWorker
3/17/2014Microsoft confidential15
• If you have some long-running code that you want to execute on a background thread, the
BackgroundWorker class is a good solution
• Still supported in Windows Phone 8!
• Supports Cancellation and Progress reports
• You can get the same behaviour using Tasks
Executing Code on a Background Thread
3/17/2014Microsoft confidential16
private void LaunchTaskButton_Click(object sender, RoutedEventArgs e)
{
BackgroundWorker bgw = new BackgroundWorker();
bgw.RunWorkerCompleted += ((s, a) =>
MessageBox.Show("BackgroundWorker has completed, result: " + (int)a.Result)
);
bgw.DoWork += ((s, a) =>
{
// Simulate some long running work
Thread.Sleep(5000);
// Return the result
a.Result = 1234;
});
// Now start execution
bgw.RunWorkerAsync();
}
BackgroundWorker
3/17/2014Microsoft confidential17
private async void LaunchTaskButton_Click(object sender, RoutedEventArgs e)
{
int result = await Task.Factory.StartNew<int>(() =>
{
// Simulate some long running work
Thread.Sleep(5000);
// Return the result
return 4321;
}
);
MessageBox.Show("BackgroundWorker has completed, result is: " + result);
}
Task Equivalent
3/17/2014Microsoft confidential18
BackgroundWorker bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.RunWorkerCompleted += ((s, a) => MessageBox.Show("BackgroundWorker has completed, result: " + (int)a.Result));
bgw.ProgressChanged += ((s, a) => {
// Progress Indicator value must be between 0 and 1
SystemTray.GetProgressIndicator(this).Value = (double)a.ProgressPercentage/100.0; });
bgw.DoWork += ((s, a) => {
// Simulate some long running work
for (int i = 0; i < 10; i++)
{
Thread.Sleep(500);
// Report progress as percentage completed
bgw.ReportProgress(i * 10);
}
a.Result = 1234; // Return the result
});
// Now start execution
bgw.RunWorkerAsync();
BackgroundWorker with Progress Reporting
3/17/2014Microsoft confidential19
IProgress<int> progressReporter = new Progress<int>((percentComplete) =>
// Progress Indicator value must be between 0 and 1
SystemTray.GetProgressIndicator(this).Value = (double)percentComplete / 100.0 );
int result = await Task.Factory.StartNew<int>(() =>
{
// Simulate some long running work
for (int i = 0; i < 10; i++)
{
Thread.Sleep(500);
// Report progress as percentage completed
progressReporter.Report(i * 10);
}
// Return the result
return 4321;
} );
MessageBox.Show("BackgroundWorker has completed, result is: " + result);
Task with Progress Reporting
3/17/2014Microsoft confidential20
BackgroundWorker bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = true;
bgw.RunWorkerCompleted += ((s, a) =>
{
if (a.Cancelled)
MessageBox.Show("BackgroundWorker was cancelled");
else
MessageBox.Show("BackgroundWorker has completed, result: " + (int)a.Result);
} );
bgw.ProgressChanged += ((s, a) => { ... });
bgw.DoWork += ((s, a) =>
{
// Simulate some long running work
for (int i = 0; i < 10; i++)
{
Thread.Sleep(500);
// Report progress as percentage completed
bgw.ReportProgress(i * 10);
// Have we been cancelled?
BackgroundWorker with Cancellation
3/17/2014Microsoft confidential21
bgw.DoWork += ((s, a) =>
{
// Simulate some long running work
for (int i = 0; i < 10; i++)
{
Thread.Sleep(500);
// Report progress as percentage completed
bgw.ReportProgress(i * 10);
// Have we been cancelled?
if (bgw.CancellationPending)
BackgroundWorker with Cancellation
3/17/2014Microsoft confidential22
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
try
{
int result = await Task.Factory.StartNew<int>(() =>
{
// Simulate some long running work
for (int i = 0; i < 10; i++)
{
Thread.Sleep(500);
// Have we been cancelled?
cancellationToken.ThrowIfCancellationRequested();
}
return 4321; // Return the result
}, cancellationToken);
MessageBox.Show("BackgroundWorker has completed, result is: " + result);
}
catch (OperationCanceledException ex) {
MessageBox.Show("Task BackgroundWorker was cancelled");
}
Task with Cancellation
3/17/2014Microsoft confidential23
• C#5 and VB.NET add first-class support for asynchronous programming
• Methods that return void, Task or Task<TResult> can be called using the await modifier
• The await modifier causes the caller to suspend execution and wait for completion of the
async task
• When complete, the return result and any exceptions are automatically marshalled back to
the originating context
• Execution continues where it left off – makes async code appear synchronous!
• Methods that make calls using await must themselves be marked with the async modifier
Summary
3/17/2014
The information herein is for informational
purposes only an 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.
© 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.
MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION
IN THIS PRESENTATION.

Más contenido relacionado

La actualidad más candente

Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
บทที่1
บทที่1บทที่1
บทที่1Palm Unnop
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionAhmed Swilam
 
No need to leave Connections. Bring your Domino applications into the Activit...
No need to leave Connections. Bring your Domino applications into the Activit...No need to leave Connections. Bring your Domino applications into the Activit...
No need to leave Connections. Bring your Domino applications into the Activit...LetsConnect
 
Apache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual HostingApache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual Hostingwebhostingguy
 
Apache Server Tutorial
Apache Server TutorialApache Server Tutorial
Apache Server TutorialJagat Kothari
 
Apache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya KulkarniApache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya Kulkarniwebhostingguy
 
Vulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing LevelsVulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing LevelsPositive Hack Days
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideSharebiyu
 

La actualidad más candente (19)

Java Networking
Java NetworkingJava Networking
Java Networking
 
บทที่1
บทที่1บทที่1
บทที่1
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
 
Apache Web Server Setup 3
Apache Web Server Setup 3Apache Web Server Setup 3
Apache Web Server Setup 3
 
TO Hack an ASP .NET website?
TO Hack an ASP .NET website?  TO Hack an ASP .NET website?
TO Hack an ASP .NET website?
 
No need to leave Connections. Bring your Domino applications into the Activit...
No need to leave Connections. Bring your Domino applications into the Activit...No need to leave Connections. Bring your Domino applications into the Activit...
No need to leave Connections. Bring your Domino applications into the Activit...
 
Apache web service
Apache web serviceApache web service
Apache web service
 
Apache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual HostingApache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual Hosting
 
Apache Server Tutorial
Apache Server TutorialApache Server Tutorial
Apache Server Tutorial
 
Apache Ppt
Apache PptApache Ppt
Apache Ppt
 
Apache
ApacheApache
Apache
 
Apache Web Server Setup 2
Apache Web Server Setup 2Apache Web Server Setup 2
Apache Web Server Setup 2
 
Apache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya KulkarniApache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya Kulkarni
 
Vulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing LevelsVulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing Levels
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
URL Class in JAVA
URL Class in JAVAURL Class in JAVA
URL Class in JAVA
 
Apache web server
Apache web serverApache web server
Apache web server
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 

Similar a Async and Await Programming on Windows Phone 8

Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyDavid Gómez García
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingMax Kleiner
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4Wei Sun
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Codemotion
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformLucio Grenzi
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docxPlease look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docxrandymartin91030
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfEngmohammedAlzared
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26Max Kleiner
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
MobConf - session on C# async-await on 18june2016 at Kochi
MobConf - session on C# async-await on 18june2016 at KochiMobConf - session on C# async-await on 18june2016 at Kochi
MobConf - session on C# async-await on 18june2016 at KochiPraveen Nair
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotXamarin
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
Flow based programming in golang
Flow based programming in golangFlow based programming in golang
Flow based programming in golangAnton Stepanenko
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 

Similar a Async and Await Programming on Windows Phone 8 (20)

Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docxPlease look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
MobConf - session on C# async-await on 18june2016 at Kochi
MobConf - session on C# async-await on 18june2016 at KochiMobConf - session on C# async-await on 18june2016 at Kochi
MobConf - session on C# async-await on 18june2016 at Kochi
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien Pouliot
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
Flow based programming in golang
Flow based programming in golangFlow based programming in golang
Flow based programming in golang
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
 

Más de Oliver Scheer

Windows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone StoreWindows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone StoreOliver Scheer
 
Windows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app PurchaseWindows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app PurchaseOliver Scheer
 
Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsOliver Scheer
 
Windows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using SpeechWindows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using SpeechOliver Scheer
 
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and BluetoothWindows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and BluetoothOliver Scheer
 
Windows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationWindows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationOliver Scheer
 
Windows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesWindows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesOliver Scheer
 
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen NotificationsWindows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen NotificationsOliver Scheer
 
Windows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsWindows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsOliver Scheer
 
Windows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application LifecycleWindows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application LifecycleOliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentWindows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentOliver Scheer
 
Windows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 ApplicationsWindows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 ApplicationsOliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 
Windows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 ApplicationsWindows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 ApplicationsOliver Scheer
 

Más de Oliver Scheer (15)

Windows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone StoreWindows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone Store
 
Windows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app PurchaseWindows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app Purchase
 
Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and Maps
 
Windows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using SpeechWindows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using Speech
 
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and BluetoothWindows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
 
Windows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationWindows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App Communication
 
Windows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesWindows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone Resources
 
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen NotificationsWindows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
 
Windows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsWindows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background Agents
 
Windows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application LifecycleWindows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application Lifecycle
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentWindows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
 
Windows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 ApplicationsWindows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 Applications
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 
Windows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 ApplicationsWindows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 Applications
 

Último

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Último (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Async and Await Programming on Windows Phone 8

  • 1. Oliver Scheer Senior Technical Evangelist Microsoft Deutschland http://the-oliver.com Async and Await Programming on Windows Phone 8 await async
  • 2. Agenda 3/17/2014Microsoft confidential2 async and await in C#5 Task Programming Model How awaitable objects work The new way to do parallel processing Replacing BackgroundWorker with async Learn why you’ll never use Thread or Threadpool again!
  • 3. • Windows Phone 7.1 Base Class Libraries used .NET 4.0 patterns to support asynchronous programming • Async programming model: BeginXYZ, EndXYZ methods • Example: HttpWebRequest BeginGetResponse and EndGetResponse methods • Event async pattern: Setup a Completed event handler, then call XYZAsync() to start operation • Example: WebClient DownloadStringAsync method and DownloadStringCompleted event • Windows Phone 8 includes many WinRT APIs • Any API that potentially takes more than 50ms to complete is exposed as an asynchronous method using a new pattern: Task Programming Model • Asynchronous programming is a first class citizen of WinRT, used for File I/O, Networking etc • Task-based programming is becoming the way to write asynchronous code • Many new APIs in Windows Phone 8 now and in the future will offer only a Task-based API Async Methods and Task Programming Model 3/17/2014Microsoft confidential3
  • 4. Keeping UI Fast and Fluid Comparing blocking File I/O using WP7.1 with TPM File I/O in WP8 3/17/2014Microsoft confidential4 TIME UI Thread var isf = IsolatedStorageFile.GetUserStoreForApplication(); using (var fs = new IsolatedStorageFileStream( "CaptainsLog.store", FileMode.Open, isf)) { StreamReader reader = new StreamReader(fs); theData = reader.ReadToEnd(); reader.Close(); };
  • 5. StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appdata:///local/CaptainsLog.store ")); Stream readStream = await StorageFile.OpenStreamForReadAsync(); using (StreamReader reader = new StreamReader(readStream)) { theData = await reader.ReadToEndAsync(); } Keeping UI Fast and Fluid Comparing blocking File I/O using WP7.1 with TPM File I/O in WP8 3/17/2014Microsoft confidential5 TIME UI Thread
  • 6. Making Asynchronous Code Look Synchronous 3/17/2014Microsoft confidential6 private async Task<string> LoadFromLocalFolderAsync() { StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appdata:///local/CaptainsLog.store ")); Stream readStream = await storageFile.OpenStreamForReadAsync(); using (StreamReader reader = new StreamReader(readStream)) { theData = await reader.ReadToEndAsync(); } } Original Context ThreadpoolTIME
  • 7. Simpler for Developers to Write Asynchronous Code 3/17/2014 Microsoft confidential7 private async void SomeMethod() { … string theData = await LoadFromLocalFolderAsync(); TextBox1.Text = theData; … } private async Task<string> LoadFromLocalFolderAsync() { ... } All Async methods must return void, Task or Task<TResult> Caller can use the await keyword to pause until the async operation has completed execution on a Threadpool thread It automatically marshals back to the originating context, so no need to use the Dispatcher to set UI objects on the UI thread All methods that contain calls to awaitables must be declared using the async keyword When the async code completes , it ‘calls back’ and resumes where it left off, passing back the return value
  • 8. • Marking a method with the async keyword causes the C# or Visual Basic compiler to rewrite the method’s implementation using a state machine • Using this state machine the compiler can insert points into the method at which the method can suspend and resume its execution without blocking a thread • These points are inserted only where you explicitly use the await keyword • When you await an asynchronous operation that’s not yet completed: • Compiler packages up all the current state of the calling method and preserves it on the heap • Function returns to the caller, allowing the thread on which it was running to do other work • When the awaited operation later completes, the method’s execution resumes using the preserved state Compiler Transformations 3/17/2014Microsoft confidential8
  • 9. private async void SomeMethod() { string theData = await LoadFromLocalFolderAsync(); TextBox1.Text = theData; } Freeing Up the Calling Thread 3/17/2014Microsoft confidential9
  • 10. private async void SomeMethod() { await LoadFromLocalFolderAsync(); [Preserve state on heap] } [Calling thread free to do other work] Freeing Up the Calling Thread 3/17/2014Microsoft confidential10 [Calling thread free to do other work] [Calling thread free to do other work] [Calling thread free to do other work]
  • 11. { [Restore Context] string theData = [Result from LoadFromLocalFolder()] TextBox1.Text = theData; } private async void SomeMethod() { await LoadFromLocalFolder(); [Preserve state on heap] } [Calling thread free to do other work] Freeing Up the Calling Thread 3/17/2014Microsoft confidential11 [Calling thread free to do other work] [Calling thread free to do other work] [Calling thread free to do other work]
  • 12. • Error Handling is simpler • Just use try…catch around the async code, same as with synchronous code • Exceptions thrown while code is executing asynchronously are surfaced back on the calling thread private async void SomeMethod() { try { string theData = await LoadFromLocalFolder(); TextBox1.Text = theData; } catch (Exception ex) { // An exception occurred from the async operation } } Error Handling 3/17/2014Microsoft confidential12
  • 13. • No, you can call async methods without await • Called method still executes on background thread • The calling thread does not wait for the result • Only feasible for async methods that return void or Task, not Task<TResult> • Intellisense warns you when you do this Must I use await with async methods? 3/17/2014Microsoft confidential13
  • 14.
  • 16. • If you have some long-running code that you want to execute on a background thread, the BackgroundWorker class is a good solution • Still supported in Windows Phone 8! • Supports Cancellation and Progress reports • You can get the same behaviour using Tasks Executing Code on a Background Thread 3/17/2014Microsoft confidential16
  • 17. private void LaunchTaskButton_Click(object sender, RoutedEventArgs e) { BackgroundWorker bgw = new BackgroundWorker(); bgw.RunWorkerCompleted += ((s, a) => MessageBox.Show("BackgroundWorker has completed, result: " + (int)a.Result) ); bgw.DoWork += ((s, a) => { // Simulate some long running work Thread.Sleep(5000); // Return the result a.Result = 1234; }); // Now start execution bgw.RunWorkerAsync(); } BackgroundWorker 3/17/2014Microsoft confidential17
  • 18. private async void LaunchTaskButton_Click(object sender, RoutedEventArgs e) { int result = await Task.Factory.StartNew<int>(() => { // Simulate some long running work Thread.Sleep(5000); // Return the result return 4321; } ); MessageBox.Show("BackgroundWorker has completed, result is: " + result); } Task Equivalent 3/17/2014Microsoft confidential18
  • 19. BackgroundWorker bgw = new BackgroundWorker(); bgw.WorkerReportsProgress = true; bgw.RunWorkerCompleted += ((s, a) => MessageBox.Show("BackgroundWorker has completed, result: " + (int)a.Result)); bgw.ProgressChanged += ((s, a) => { // Progress Indicator value must be between 0 and 1 SystemTray.GetProgressIndicator(this).Value = (double)a.ProgressPercentage/100.0; }); bgw.DoWork += ((s, a) => { // Simulate some long running work for (int i = 0; i < 10; i++) { Thread.Sleep(500); // Report progress as percentage completed bgw.ReportProgress(i * 10); } a.Result = 1234; // Return the result }); // Now start execution bgw.RunWorkerAsync(); BackgroundWorker with Progress Reporting 3/17/2014Microsoft confidential19
  • 20. IProgress<int> progressReporter = new Progress<int>((percentComplete) => // Progress Indicator value must be between 0 and 1 SystemTray.GetProgressIndicator(this).Value = (double)percentComplete / 100.0 ); int result = await Task.Factory.StartNew<int>(() => { // Simulate some long running work for (int i = 0; i < 10; i++) { Thread.Sleep(500); // Report progress as percentage completed progressReporter.Report(i * 10); } // Return the result return 4321; } ); MessageBox.Show("BackgroundWorker has completed, result is: " + result); Task with Progress Reporting 3/17/2014Microsoft confidential20
  • 21. BackgroundWorker bgw = new BackgroundWorker(); bgw.WorkerReportsProgress = true; bgw.WorkerSupportsCancellation = true; bgw.RunWorkerCompleted += ((s, a) => { if (a.Cancelled) MessageBox.Show("BackgroundWorker was cancelled"); else MessageBox.Show("BackgroundWorker has completed, result: " + (int)a.Result); } ); bgw.ProgressChanged += ((s, a) => { ... }); bgw.DoWork += ((s, a) => { // Simulate some long running work for (int i = 0; i < 10; i++) { Thread.Sleep(500); // Report progress as percentage completed bgw.ReportProgress(i * 10); // Have we been cancelled? BackgroundWorker with Cancellation 3/17/2014Microsoft confidential21
  • 22. bgw.DoWork += ((s, a) => { // Simulate some long running work for (int i = 0; i < 10; i++) { Thread.Sleep(500); // Report progress as percentage completed bgw.ReportProgress(i * 10); // Have we been cancelled? if (bgw.CancellationPending) BackgroundWorker with Cancellation 3/17/2014Microsoft confidential22
  • 23. var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; try { int result = await Task.Factory.StartNew<int>(() => { // Simulate some long running work for (int i = 0; i < 10; i++) { Thread.Sleep(500); // Have we been cancelled? cancellationToken.ThrowIfCancellationRequested(); } return 4321; // Return the result }, cancellationToken); MessageBox.Show("BackgroundWorker has completed, result is: " + result); } catch (OperationCanceledException ex) { MessageBox.Show("Task BackgroundWorker was cancelled"); } Task with Cancellation 3/17/2014Microsoft confidential23
  • 24.
  • 25. • C#5 and VB.NET add first-class support for asynchronous programming • Methods that return void, Task or Task<TResult> can be called using the await modifier • The await modifier causes the caller to suspend execution and wait for completion of the async task • When complete, the return result and any exceptions are automatically marshalled back to the originating context • Execution continues where it left off – makes async code appear synchronous! • Methods that make calls using await must themselves be marked with the async modifier Summary 3/17/2014
  • 26. The information herein is for informational purposes only an 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. © 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. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.