MobConf - session on C# async-await on 18june2016 at Kochi

Post on 11-Feb-2017

113 views 0 download

Transcript of MobConf - session on C# async-await on 18june2016 at Kochi

1

2

3

async / awaitan asynchronous way

Saturday, 18 June 2016 @ Athulya Hall, InfoparkKochi

How much time it takes toload your website?

praveen nair• sr. manager, technology @ orion india systems• head_of (architecture, r&d and technology);

• articles, blogging, teaching, speaking, guiding, consulting• microsoft mvp (2006-11), mcsd, pmp• pmi india champion• web: ninethsense.com• twitter: @ninethsesne

How much time it takes an operation to complete?

The 50ms Rule• Operations should be made asynchronous if they

“could take longer than 50 milliseconds to execute”

• Reference: https://blogs.msdn.microsoft.com/windowsappdev/2012/03/20/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime/

• Reference: http://blog.stephencleary.com/2013/04/ui-guidelines-for-async.html

Parallel Programming• Multiple cores, processors, or computers• For the sake of better performance• …improve user’s experience

Does your basic .NET application runs on single core or multi?

Different ways to initiate tasks• Asynchronous Delegates• BeginInvoke()

• Thread• ThreadPool• BackgroundWorker• Task• async await

Asynchronous programming• Asynchronous Programming Model• Eg: FileStream.BeginRead, .EndRead

• Event-based Asynchronous Pattern• BackgroundWorker

• Task-based Asynchronous Pattern• System.Threading.Tasks• async - await

C# 5.0 (Compiler feature, not CLR)

.NET 4.5

Visual Studio 2012+

async … await

What Happens in an Async Method?

MSDN

Reference: https://msdn.microsoft.com/en-us/library/mt674882.aspx

what you feel?• A return statement in the middle of a method()• GOTO statement in BASIC or C Language

async … awaitpublic async Task<int> DownloadHomepage() {

…await ……return 0;

}

• async indicate that it contains code that can run asynchronously• await - stop execution at that point and wait until the task

completes.• should contain at least one await expression or statement

• warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

• should return a Task, Task<TResult> or void

‘requirements’ matters• Blocking code / synchronous• Non-blocking code / asynchronous

async … await

async void HandleTouchUpInside (object sender, EventArgs e) { ResultLabel.Text = "loading..."; ResultTextView.Text = "loading...\n";

// await! control returns to the caller var intResult = await DownloadHomepage();

// when the Task<int> returns, the value is available //and we can display on the UI ResultLabel.Text = "Length: " + intResult ; }

async … awaitpublic async Task<int> DownloadHomepage() { var httpClient = new HttpClient(); Task<string> contentsTask = httpClient.GetStringAsync("http://mobconf.com");

// control returns to the caller and the task continues // to run on another thread string contents = await contentsTask;

ResultEditText.Text += "method continues after async call…";

// After contentTask completes, you can calculate // the length of the string. int exampleInt = contents.Length;

ResultEditText.Text += "Downloaded the html and found out the length. "; ResultEditText.Text += contents; // dump the entire HTML

// Task<TResult> returns an object of type TResult, // in this case int return exampleInt; }

Exception Handling1. stored in the task 2. thrown when the task is awaited3. handle inside a try-catch block

Pros & Cons• Improves responsiveness at a slight cost of memory• improves scalability by reducing memory/thread

usage• Multiple I/O bound methods in parallel• Readability / Clean Code• Debuggability / Exception Handling

Pitfalls / keep in mind• Don’t assume that parallel is always faster• Beware of shared memory locations• Prefer Task() over void() – due to error handling• Avoid mixing blocking and non-blocking code –

beware of deadlocks, poor error handling• Avoid async-await for very short methods()• Avoid over-parallelization – mind # of cores• Avoid parallel loops on UI thread

Thank You“A person who is interrupted while performing a task takes 50% more time to complete it and make 50% more errors.”

― David Brooks