Top Banner
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
33

Asynchronous Programming with C# and WinRT

Feb 24, 2016

Download

Documents

NARA

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. Table of Contents. Synchronous Programming Problems - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

Synchronous Programming

Page 4: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

Resource Access Problems

Live Demo

Page 8: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

CPU-demanding Tasks Problems

Live Demo

Page 10: Asynchronous Programming with  C# and WinRT

Asynchronous Programming

Page 11: Asynchronous Programming with  C# and WinRT

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 it11

Page 12: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

Asynchronous Programming in C#

Page 15: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

Tasks with async & awaitThe C# 5 approach to asynchronous

programming

Page 20: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

Using built-in Async Methods

Live Demo

Page 25: Asynchronous Programming with  C# and WinRT

Making Asynchronous Methods

Offloading heavy computations to other threads

Page 26: Asynchronous Programming with  C# and WinRT

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 thread

26

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

Page 27: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

Creating Your Own Async Methods

Live Demo

Page 29: Asynchronous Programming with  C# and WinRT

Error Handling in async & await Code

Try-catch statements with asynchronous code

Page 30: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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: Asynchronous Programming with  C# and WinRT

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

програмиране за деца – безплатни курсове и уроцибезплатен 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, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране

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

?? ? ?

??? ?

?

? ?

??

?

?

? ?

Questions?

?

Asynchronous Programming with C#

and WinRT

http://academy.telerik.com

Page 33: Asynchronous Programming with  C# and WinRT

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