Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev...

33
Asynchronous Programming with C# and WinRT Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation www.telerik.com Technical Trainer itgeorge.net

Transcript of Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev...

Page 1: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Asynchronous Programming with

C# and WinRTSync vs. Async programming, Tasks,

C# 5 async and await, WinRT async operations

George Georgiev

Telerik Corporationwww.telerik.com

Technical Traineritgeorge.net

Page 2: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Table of Contents

2

Synchronous Programming Problems CPU-demanding tasks, Resource

access Asynchronous Programming

Benefits & Difficulties Asynchronous Programming in C#

Threads, Tasks, Callback problems Async Programming with C# and WinRT Tasks with async & await Making Asynchronous methods Error handling async & await code

Page 3: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Synchronous Programming

Page 4: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Synchronous Programming

Executing program components sequentially i.e. "Sequential programming" Actions happen one after another Uses a single thread of a single

process Components wait for previous components to finish

Program resources are accessible at all points

4

Page 5: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Synchronous Programming Problems

Problems of Sync Programming If one component blocks,

entire program blocks

UI may become unresponsive

No utilization of multi-core systems

CPU demanding tasks delay execution of all other tasks

Accessing resources blocks entire program Especially problematic with web

resources5

Page 6: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Synchronous Programming Problems

Resource access problems Resources may be large

While loading, UI blocks

Program stops responding

Resources may be web-based Slow connections mean slow loading

Server may hang

While accessing, sync programs stop all other operations

6

Page 7: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Resource Access Problems

Live Demo

Page 8: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Synchronous Programming Problems

CPU-demanding tasks problems CPU-demanding problems will

freeze the program Program stops responding

Some CPU-demanding tasks are many smaller, independent tasks Sync programming must sequentially

go through them

8

Page 9: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

CPU-demanding Tasks Problems

Live Demo

Page 10: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Asynchronous Programming

Page 11: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Asynchronous Programming

Program components can execute in parallel Some actions run alongside other

actions Each action happens in a separate

thread Independent components don't wait for each other

Program resources shared between threads If one thread uses a resources,

others shouldn't use it

11

Page 12: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Asynchronous Programming Benefits

Benefits of Async Programming If component blocks, other

components still run Until they need a resource from blocked

component

UI runs separately Always responsive

Utilization of multi-core systems Each core executes one or several

threads

CPU demanding tasks on "background" threads

Resource access runs on "background" threads

12

Page 13: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Asynchronous Programming

Difficulties Hard to imagine which code run at some time

Hard to notify a "component" has executed So far, callbacks were the way

Have to ensure callback runs in appropriate context (e.g. same thread it started in)

Have to protect resources One thread uses a resources, others

wait for it Hard to synchronize resource access

Deadlocks and race conditions can occur

13

Page 14: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Asynchronous Programming in C#

Page 15: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Async Programming in C#

Thread – smallest, independent piece of a program, executable by the OS "Subprocess" Usually contained inside a process

C# is a multi-threaded language by design Process/program can manage

multiple threads Threads execute in parallel

(handled by OS & CPU) Thread control mechanisms are

available in C#

15

Page 16: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Async Programming in C#

Threads and ThreadPool Direct control over thread execution

Callbacks for Thread events

Tasks – abstraction over Threads Represent work which will be

completed Wrap delegates/lambdas into objects

with Result

Task<int> represents an integer to be calculated

Handle threading "under the hood"

Callbacks for thread events

16

Page 17: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Async Programming with C#

Problems with callbacks Code becomes hard to track

Exceptions are not propagated properly

Thread context is not saved i.e. a callback defined in one thread

is not guaranteed to work on same thread

17

Page 18: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Async Programming with C#

Thread context problem example: UI thread attaches a callback to a

calculation method

Callback should prints results in a ListView

Calculation method completes -> callback is run But not on UI thread

The callback has no access to the UI thread's resources and we get a "wrong thread" exception 18

Page 19: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Tasks with async & awaitThe C# 5 approach to asynchronous

programming

Page 20: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Tasks with async & await

Tasks + async & await = modern approach Tasks can be "awaited" Methods can be marked as

asynchronous async and await keywords

Make sense when used together Enable "inline" multithreaded code Remove callbacks from code

("flatten") Code looks like normal sync code

Compiler generates appropriate callbacks

20

Page 21: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Tasks with async & await

async keyword – used on a method signature Marks a method, which can be

asynchronous Doesn't make it asynchronous – you

do, through an "await"

Wraps any returned result in a Task i.e. method return value is Task (or

void)

Means "this could wait for a resource or operation" If it starts waiting, return to the

calling method

When the wait is over, go back to called method

21

Page 22: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Tasks with async & await

await keyword Used in a method which has async

keyword Saves the context in a state

machine Marks waiting for a resource

Resource should be a Task<T>

Returns T result from Task<T>, when it completes

Means await the completion of a task While awaiting -> let the rest of the

program run

Awaiting over -> continue executing the next statements in the method

22

Page 23: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Tasks with async & await

Using built-in Async methods WinRT APIs are mainly

asynchronous Any operation which could run for

>50ms Is asynchronous in WinRT

Should be asynchronous in your code

Return some type of IAsyncOperation Can be awaited just like a Task

Behaves almost the same as a task

Limited control, but convertible to Task

23

Page 24: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Using built-in Async Methods

Live Demo

Page 25: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Making Asynchronous Methods

Offloading heavy computations to other threads

Page 26: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Making Asynchronous Methods

Any synchronous method can be used asynchronously

Tasks basically call a method In most cases Task.Run() will be

enough Returns a Task which can be awaited

Under the hood: Get a free thread

Execute the method in that thread26

Task<List<int>> primesTask = Task.Run(()=>CalcPrimes(0, 1000));List<int> primes = await primesTask;

Page 27: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Making Asynchronous Methods

"Patterns" to make your code asynchronous Make a method which returns a

Task, which is Run Call the method and "await" the task

result

Make an async method with a return type of Task (or void) (Optionally) start awaiting a result or

action

Return the result as a value (if you have a result)

The compiler will wrap it in a Task

Call the method and await the task result

27

Page 28: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Creating Your Own Async Methods

Live Demo

Page 29: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Error Handling in async & await Code

Try-catch statements with asynchronous code

Page 30: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Error Handling async & await

With async & await error-handling is straightforward Wrap error-prone code in try

statement

Catch exceptions

No callbacks in code, so no problem to write try-catch like in normal sync code

Under the hood: Try-catch is associated with the state

machines of the "await"s in it 30

Page 31: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Summary Store apps should be heavily asynchronous

Tasks with async & await Modern approach to asynchronous

programming

Make code easier to read, take care of thread context and other callback problems

In-depth reading on async & await in WinRT

Asynchronous programming will never be easy Be wary of deadlocks, race

conditions and the like

31

Page 32: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Asynchronous Programming with C#

and WinRT

http://academy.telerik.com

Page 33: Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation  Technical Trainer itgeorge.net.

Exercises1. Write an app, which calculates primes in a

range. Then gets all of the primes and for each

prime: Finds another prime, which begins with the same

digit as the first ends in Concatenates the two primes (first+second)

According to a setting: Either finds which of the concatenations are also

primes and lists them Or finds which of the concatenations are NOT

primes and lists them

The program should provide UI for 4 calculation requests, each with prime range input, list primes/list non-primes setting and display for the listed concatenations

The UI should always be responsive

33