Asynchronous Programming with C# and WinRT

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Coding JavaScript the expressive way Learning & Development Telerik Software Academy.
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Touch and Gestures with Xamarin Forms
Telerik School Academy ASP.NET MVC.
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
With Mocha and Karma Telerik Academy Telerik Software Academy.
C# Fundamentals – Part I
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Telerik Software Academy End-to-end JavaScript Applications.
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
"Synchronous" vs. Asynchronous programming, Tasks, C# 4.5 features async and await Telerik Academy Plus Concurrent C#
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team Telerik Software Academy.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Presentation transcript:

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 www.telerik.com

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

Synchronous Programming

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

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

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

Resource Access Problems Live Demo

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

CPU-demanding Tasks Problems Live Demo

Asynchronous Programming

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

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

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

Asynchronous Programming in C#

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#

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

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

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

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

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

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

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

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

Using built-in Async Methods Live Demo

Making Asynchronous Methods Offloading heavy computations to other threads

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;

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

Creating Your Own Async Methods Live Demo

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

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

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

Asynchronous Programming with C# and WinRT http://academy.telerik.com

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