C# 5 deep drive into asynchronous programming

19
C# 5: Deep Drive into Asynchronous Programming By- Praveen Kumar Prajapati Blog: praveenprajapati.wordpress.com

description

BDotnet Session on C# 5

Transcript of C# 5 deep drive into asynchronous programming

Page 1: C# 5 deep drive into asynchronous programming

C# 5: Deep Drive into Asynchronous Programming

By- Praveen Kumar Prajapati

Blog: praveenprajapati.wordpress.com

Page 2: C# 5 deep drive into asynchronous programming

Agenda What’s asynchrony

Related Terms and Need of Asynchrony

Why TPL: The Free Lunch is Over

C# 4: Task Parallel Library

C# 4: TPL Demo

C# 5 : Asynchronous Programming

C# 5 : Behind the Scene

C# 5 : Async Demo

Summery

Page 3: C# 5 deep drive into asynchronous programming

What’s asynchrony What’s asynchrony?

Greek origin

a (not)

syn (together with)

chronos (time)

Multiple parties evolving in time independently

Not being blocked

Synchronous Wait for result before returning string DownloadString(...);

Asynchronous Return now, call back with result void DownloadStringAsync(..., Action<string> callback);

Page 4: C# 5 deep drive into asynchronous programming

Related Concepts Multithreading

Use of multiple threads

Concurrency Order in which multiple tasks execute is not determined

Parallelism True simultaneous execution (e.g. multicore)

Page 5: C# 5 deep drive into asynchronous programming

Need of Asynchrony

Increasingly connected applications More latency

More UI responsiveness problems

More scalability issues

Asynchronous programming Becoming the norm in responsive, scalable apps

More relevant to Metro Style Apps and Window Phone Apps

Async-only APIs, e.g., JavaScript and Silverlight

Page 6: C# 5 deep drive into asynchronous programming

Asynchronous Programming Model

DownloadDataAsync

ParseResponse

DisplayPhotos

UI Thread

UI Message

s

Hang

Page 7: C# 5 deep drive into asynchronous programming

Why TPL : The Free Lunch is Over

A paradigm shift Then: Faster clocks

Now: More cores => End of the Free Lunch

The Free Lunch is Over By Herb Sutter in Feb/Mar 2005

The Free Lunch Is Over

-A Fundamental Turn Toward Concurrency in Software

Why You Don’t Have 10GHz Today

Page 8: C# 5 deep drive into asynchronous programming

The Free Lunch is Over

Page 9: C# 5 deep drive into asynchronous programming

Single to Multiple Core Transition

Page 10: C# 5 deep drive into asynchronous programming

C# 4 : Task Parallel Library

“Applications will increasingly need to be concurrent if they want to fully exploit continuing exponential CPU throughput gains”

What would be the optimum number of threads for this machine?

But how to decide the degree of concurrency? What if server gets more core in future – Change in underlying hardware?

Page 11: C# 5 deep drive into asynchronous programming

C# 4 : Task Parallel Library

The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available.

In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details.

By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

Page 12: C# 5 deep drive into asynchronous programming

Thread vs. Task Task: A Task is a future or a promise. (Some people use

those two terms synonymously, some use them differently, nobody can agree on a precise definition.)

Basically, a Task<T> "promises" to return you a T, but not right now .

Thread: A Thread is one of many ways to fulfill that promise. But not every Task needs a Thread. If the value you are waiting for comes from the file system or a database or the network, then there is no need for a thread. The Task might just register a callback to receive the value when the disk is done seeking.

TPL Demo

Page 13: C# 5 deep drive into asynchronous programming

C# 5 : Asynchronous Programming

New Keyword introduces: async

Await

Asynchronous Methods As simple as synchronous code

Unifies computational, network and I/O asynchrony

More scalable servers

More responsive UI

Page 14: C# 5 deep drive into asynchronous programming

C# 5 : Behind the Scenepublic async Task<XElement> GetXmlAsync(string url) { var client = new HttpClient(); var response = await client.GetAsync(url); var text = response.Content.ReadAsString(); return XElement.Parse(text);}

public Task<XElement> GetXmlAsync(string url) { var tcs = new TaskCompletionSource<XElement>(); var client = new HttpClient(); client.GetAsync(url).ContinueWith(task => { var response = task.Result; var text = response.Content.ReadAsString(); tcs.SetResult(XElement.Parse(text)); }); return tcs.Task;}

Page 15: C# 5 deep drive into asynchronous programming

C# 5 : Async Demo

Demo: Use of async and await

How it reduces efforts and make code better

Page 16: C# 5 deep drive into asynchronous programming

Some Point to Remember For any async block it is important to have at least one

await, otherwise the whole block will work synchronously.

Any async method should postfix Async (as a rule), so your method name should look like MyMethodAsync which you put an async keyword before it.

Exceptions to the convention can be made where an event, base class, or interface contract suggests a different name.

Any async method can return void(call and forget), Task or Task<T> based on the Result the await method sends.

Everything is managed by a State Machine Workflow by the compiler

Page 17: C# 5 deep drive into asynchronous programming

Summery

Asynchronous Programming and related terms

Why it is so relevant in current days

Free Lunch is Over

TPL and Task

New Kew words : async and await

Rules and recommendation for new features

Page 18: C# 5 deep drive into asynchronous programming

References

• Visual Studio Asynchronous Programminghttp://msdn.microsoft.com/en-us/vstudio/async.aspx

• Task Parallel Libraryhttp://msdn.microsoft.com/en-us/library/dd460717.aspx

• The Future of C# and VB @PDC10http://player.microsoftpdc.com/Session/1b127a7d-300e-4385-af8e-ac747fee677a

• Fabulous Adventures in Codinghttp://blogs.msdn.com/b/ericlippert

• John Skeet: Coding Bloghttp://msmvps.com/blogs/jon_skeet

Page 19: C# 5 deep drive into asynchronous programming

Thanks to You AllLet us grow

togetherKeep in touch:

Blog: praveenprajapati.wordpress.com