Top Banner
Presentation By: Live App team. Task Parallel Library(TPL)
20
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: Task parallel library presentation

Presentation By:Live App team.

Task Parallel Library(TPL)

Page 2: Task parallel library presentation

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

Page 3: Task parallel library presentation

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.

Page 4: Task parallel library presentation

Introduction(Cont.)

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

Page 5: Task parallel library presentation

Life Before Async/Await

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

Asynchronous Programming Model (APM)

Page 6: Task parallel library presentation

Life Before Async/Await(Cont.)

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

Page 7: Task parallel library presentation

Life Before Async/Await (Cont.)

• Why these Patterns are messy?

Page 8: Task parallel library presentation

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.

Page 9: Task parallel library presentation

The Lifecycle of an Async Operation

Page 10: Task parallel library presentation

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.

Page 11: Task parallel library presentation

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).

Page 12: Task parallel library presentation

Exceptions in Async Code

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

Page 13: Task parallel library presentation

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.

Page 14: Task parallel library presentation

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

Page 15: Task parallel library presentation

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) {}}

Page 16: Task parallel library presentation

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.

Page 17: Task parallel library presentation

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.

Page 18: Task parallel library presentation

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

Page 19: Task parallel library presentation

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

Page 20: Task parallel library presentation

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