Presentation is loading. Please wait.

Presentation is loading. Please wait.

Asynchronous Programming with C# and WinRT

Similar presentations


Presentation on theme: "Asynchronous Programming with C# and WinRT"— Presentation transcript:

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

2 Table of Contents 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 Synchronous Programming

4 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

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

6 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

7 Resource Access Problems
Live Demo

8 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

9 CPU-demanding Tasks Problems
Live Demo

10 Asynchronous Programming

11 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

12 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

13 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

14 Asynchronous Programming in C#

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

16 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

17 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

18 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

19 Tasks with async & await
The C# 5 approach to asynchronous programming

20 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

21 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

22 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

23 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

24 Using built-in Async Methods
Live Demo

25 Making Asynchronous Methods
Offloading heavy computations to other threads

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

27 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

28 Creating Your Own Async Methods
Live Demo

29 Error Handling in async & await Code
Try-catch statements with asynchronous code

30 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

31 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

32 Asynchronous Programming with C# and WinRT

33 Exercises 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


Download ppt "Asynchronous Programming with C# and WinRT"

Similar presentations


Ads by Google