Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation www.telerik.com Technical Trainer itgeorge.net."— Presentation transcript:

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

2 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

3

4  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

5  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 resources 5

6  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

7 Live Demo

8  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

9 Live Demo

10

11  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

12  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

13  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

14

15  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

16  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 represents an integer to be calculated  Handle threading "under the hood"  Callbacks for thread events 16

17  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

18  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

19 The C# 5 approach to asynchronous programming

20  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

21  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

22  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  Resource should be a Task  Returns T result from Task, 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

23  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

24 Live Demo

25 Offloading heavy computations to other threads

26  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 > primesTask = Task.Run(()=>CalcPrimes(0, 1000)); Task.Run(()=>CalcPrimes(0, 1000)); List primes = await primesTask;

27  "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

28 Live Demo

29 Try-catch statements with asynchronous code

30  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

31  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 In-depth reading on async & await in WinRT In-depth reading on async & await in WinRT  Asynchronous programming will never be easy  Be wary of deadlocks, race conditions and the like 31

32 форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен 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# Николай Костов - блог за програмиране http://academy.telerik.com

33 1. 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


Download ppt "Sync vs. Async programming, Tasks, C# 5 async and await, WinRT async operations George Georgiev Telerik Corporation www.telerik.com Technical Trainer itgeorge.net."

Similar presentations


Ads by Google