20
Presentation By: Live App team. Task Parallel Library(TPL)

Task parallel library presentation

Embed Size (px)

Citation preview

Presentation By:Live App team.

Task Parallel Library(TPL)

Agenda

• Introduction• Life Before Async/Await• Synchronization context• The Lifecycle of an Async Operation• Misconception about async/await• Difference between CPU bound work and I/O work• Handling Exceptions• Report Progress/Cancellation of a task• Unit Testing• Combinators• Tips and tricks

Introduction

• What is Thread?In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system.

Introduction(Cont.)

• Blocking Code VS. Non Blocking code.(Demo)

Life Before Async/Await

• example is the method on DNS that looks up the IP address for a hostname

Asynchronous Programming Model (APM)

Life Before Async/Await(Cont.)

• Event-based Asynchronous Pattern (EAP)Example Downloading webpage and display it.

Life Before Async/Await (Cont.)

• Why these Patterns are messy?

Synchronization context

• It represents a target for work• It’s been in the framework for a while, but we generally haven’t had to worry about it.• For example, in Winforms, if you get the current SynchronizationContext and do Post on it, it

does a Control.BeginInvoke. That's how Winforms gets onto the UI thread.• And ASP.Net current synchronization context, when you do Post() on it, it schedules work to be

done in its own way.• There are about 10 in the framework, and you can create more.• And this is the key way that the await keyword knows how to put you back where you were.• So when you do await, it first captures the current SyncContext before awaiting.• When it resumes, it uses SyncContext.Post() to resume "in the same place" as it was before.

The Lifecycle of an Async Operation

Misconception about async/await

• In each async method you write, some code will be before the first occurrence of the await keyword. Equally, some code is in the expression that gets awaited. This code always runs in the calling thread. Nothing interesting happens before the first await.

• This is one of the most common misconceptions about async. Async never schedules your method to run on a background thread. The only way to do that is using something like Task.Run, which is explicitly for that purpose.

Difference between CPU bound work and I/O work

CPU bound work* CPU-bound means things like LINQ-to-objects, or iterations, or computationally-intensive inner loops.*Parallel.ForEach and Task.Run are good ways to put these CPU-bound workloads on the threadpool.*Use of threads will never increase throughput on a machine that’s under load.

I/O bound work*Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.(Ex. Database requests, network access requests).

Exceptions in Async Code

Exceptions in Async Task-Returning Methodsasync Task Catcher() { try { await Thrower(); } catch (Exception) { // Execution will reach here } }

Exceptions in Async void Methods

Exceptions that leave an async void method are rethrown in the calling thread:• If there was a SynchronizationContext when the async method was called, the exception is Posted to it.• If not, it is thrown on the thread pool.

Exceptions in Async void Methods (cont.)

Handle Exceptions in Async void

• In case of Console and Windows Forms application subscribe to “AppDomain.CurrentDomain.UnhandledException” event.

• In case of Windows Store App subscribe to “Application.UnhandledException” event

AggregateException and WhenAll

List<Task> tasks = new List<Task> { Thrower1(), Thrower2()};Task result = Task.WhenAll(tasks);try{ await result ;}catch (Exception){ foreach (Exception ex in result.Exception.InnerExceptions) {}}

Combinators

1. Task.WhenAll (params Task[] tasks)• creates a task that will complete when all of the supplied tasks have completed. It will not block

the current execution but allows you to await the tasks for completion.2. Task.WaitAll(params Task[] tasks)

• will wait for all of the provided Task objects to complete execution.This will block the current execution until all tasks are done.

3. Task.WhenAny4. Task.WaitAny :

• So if you are inside an async method, you probably want to use Task.WhenAll or WhenAny and use await to get the results.

Tips n Tricks : Dispatcher

• On the Windows Platforms there is a rule that you cannot modify UI elements from secondary threads. On Microsoft's XAML based platforms there is a member that exists on most UI objects called the Dispatcher that can be used to marshal a call to the proper thread.

• Demo• The CoreDispatcherPriority enumeration has these members.

Tips n Tricks : TaskCompletionSource

• Is a class which wraps a Task whose state we can manually control. This is more easily understood with an example• It Mostly use it when only a event base API is available • Demo

Tips n Tricks : Configure await

• “Await task” uses the sync context• 1. It captures the current SyncContext before awaiting.• 2. Upon task completion, it calls SyncContext.Post() to resume “where you were before”

• You can use “await task.ConfigureAwait(false)”• This suppresses step 2; instead if possible it resumes “on the thread that completed the task”

• Demo

Tips n Tricks : DeadLock

• Async All the WayYou should avoid mixing async and blocking code. Mixed async and blocking code can cause deadlocks, more-complex error handling and unexpected blocking of context threads. The exception to this guideline is the Main method for console applications, or—if you’re an advanced user—managing a partially asynchronous codebase. Figure 5 The “Async Way” of Doing Things

• DemoTo Do This … Instead of This … Use This

Retrieve the result of a background task Task.Wait or Task.Result await

Wait for any task to complete Task.WaitAny await Task.WhenAny

Retrieve the results of multiple tasks Task.WaitAll await Task.WhenAll

Wait a period of time Thread.Sleep await Task.Delay