end to-end async and await

43
End-to-End Async and Await Vince Fabro Cardinal Solutions Practice Manager, Enterprise App Dev @vfabro

Upload: vfabro

Post on 10-May-2015

581 views

Category:

Technology


7 download

TRANSCRIPT

Page 1: End to-end async and await

End-to-End Async and Await

Vince FabroCardinal SolutionsPractice Manager, Enterprise App Dev@vfabro

Page 2: End to-end async and await

Agenda

• What is Async?• Why bother?• How does this work?• Gotchas• Best Practices & More Details• Next Steps

Page 3: End to-end async and await

Agenda

• What is Async?• Why bother?• How does this work?• Gotchas• Best Practices & More Details• Next Steps

Page 4: End to-end async and await

What is Async?

• C# 5.0 and .NET 4.5• async and await keywords • Asynchronous programming for the

masses!

Page 5: End to-end async and await

What is Async?

• Asynchronous == Parallel?• Asynchronous == Multithreaded?• Asynchronous == Easy?

Page 6: End to-end async and await

Agenda

• What is Async?

• Why bother?• How does this work?• Gotchas• Best Practices & More Details• Next Steps

Page 7: End to-end async and await

Why bother?

• Improve app responsiveness• Simplify asynchronous programming

more approachable

Simpler / More approachable than what?

Page 8: End to-end async and await

Asynchrony the good old way

• [… as opposed to the much worse older ways]

• APM and EAP

• APM – Asynchronous Programming Model– http://msdn.microsoft.com/en-us/library/ms228963%28v=vs.110%29.aspx– http://msdn.microsoft.com/en-us/magazine/cc163467.aspx

• EAP – Event-based Asynchronous Pattern– http://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx

Page 9: End to-end async and await

Asynchronous Programming Model

IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);

// Poll for completion information. while (result.IsCompleted != true){

…}// EndGetHostByName blocks until complete.IPHostEntry host = Dns.EndGetHostEntry(result);string[] aliases = host.Aliases;

.NET 2.0+

Page 10: End to-end async and await

Event-based Asynchronous Patternprivate SoundPlayer player;

private void InitializeSound(){

// Create an instance of the SoundPlayer class.player = new SoundPlayer();

// Listen for the LoadCompleted event.player.LoadCompleted +=

new AsyncCompletedEventHandler(player_LoadCompleted);

player.SoundLocation = filepathTextbox.Text;player.Play();

}

private void player_LoadCompleted(object sender, AsyncCompletedEventArgs e) { }

.NET 2.0+

Page 11: End to-end async and await

Supplanted by the TPL

• Both APM and EAP – “This pattern is no longer recommended for

new development”

• TPL Task Parallel Library– http://msdn.microsoft.com/en-us/library/

dd460693%28v=vs.110%29.aspx

.NET 4.0+

Page 12: End to-end async and await

Supplanted by the TPL.N

ET 4.0+

Page 13: End to-end async and await

Supplanted by the TPL.N

ET 4.0+

Page 14: End to-end async and await

Supplanted by the TPL

Parallel.ForEach(sourceCollection, item => Process(item));Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

// Create a task and supply a user delegateTask taskA = new Task( () =>

Console.WriteLine("Hello from taskA.")); // Start the task. taskA.Start();

// Output a message from the calling thread. Console.WriteLine("Hello from thread '{0}'.",

Thread.CurrentThread.Name); taskA.Wait();

.NET 4.0+

Page 15: End to-end async and await

The New Hotness!

• TAP – Task-based Asynchronous Pattern

• async and await

• So… Why bother?– Simpler than APM and EAP– Simpler than raw TPL

Builds on the TPL

.NET 4.5

Page 16: End to-end async and await

Task-based Asynchronous Pattern

private async Task<int> AccessTheWebAsync(){

HttpClient client = new HttpClient();

string urlContents = await client.GetStringAsync(

"http://msdn.microsoft.com");

return urlContents.Length;}

Page 17: End to-end async and await

Agenda

• What is Async?• Why bother?

• How does this work?• Gotchas• Best Practices & More Details• Next Steps

Page 18: End to-end async and await

How does this work?

Page 19: End to-end async and await
Page 20: End to-end async and await

Task-based Asynchronous Pattern

private async Task<int> AccessTheWebAsync(){

HttpClient client = new HttpClient();

string urlContents = await client.GetStringAsync(

"http://msdn.microsoft.com");

return urlContents.Length;}

1. Before await

2. Await Task

3. Post await

2. “Awaitable”

3. Continuation

0. For compiler

Page 21: End to-end async and await

How does this work?

Page 22: End to-end async and await

Gimme the Code! void IAsyncStateMachine.MoveNext() { string result = null; try { int num = state;

//if (!Stop) if (num != -3) { TaskAwaiter<string> taskAwaiter; // Machine starts with num=-1 so we enter if (num != 0) { // First (+ initial) state code, run code before await is invoked httpClient = new HttpClient(); Debug.WriteLine("before await"); // A task is invoked taskAwaiter = httpClient.GetStringAsync(url).GetAwaiter();

●●●

Page 23: End to-end async and await

Gimme the Code!

Whole Lotta Code!

Page 24: End to-end async and await

How does it work?

• Generates a state machine for every async call

• SynchronizationContext

• Continuation Tasks

Page 25: End to-end async and await

How does it work?

• SynchronizationContext– Provides a way to queue a unit of work to a

context, not to a specific thread– Keeps a queue and count of work to do– Every thread has a current context– http://msdn.microsoft.com/en-us/magazine/gg598924.aspx

Page 26: End to-end async and await

How does it work?

• SynchronizationContext Implementations:– WindowsFormsSynchronizationContext– DispatcherSynchronizationContext

• WPF and SilverLight

– WinRTSynchronizationContext– AspNetSynchronizationContext

• ASP.NET thread pool

– Default SynchronizationContext• ThreadPool

Page 27: End to-end async and await

How does it work?

• Continuation Tasks– On completion of one task, invoke another

// The antecedent task. Can also be created with Task.Factory.StartNew.Task<DayOfWeek> taskA = new Task<DayOfWeek>(() => DateTime.Today.DayOfWeek);

// The continuation. Its delegate takes the antecedent task  // as an argument and can return a different type. Task<string> continuation = taskA.ContinueWith((antecedent) =>

{ return String.Format("Today is {0}.", antecedent.Result);

});

// Start the antecedent. taskA.Start();

// Use the contuation's result. Console.WriteLine(continuation.Result);

Page 28: End to-end async and await

Task-based Asynchronous Pattern

private async Task<int> AccessTheWebAsync(){

HttpClient client = new HttpClient();

string urlContents = await client.GetStringAsync(

"http://msdn.microsoft.com");

return urlContents.Length;}

1. Before await

2. Await Task

3. Post await

2. “Awaitable”

3. Continuation

0. For compiler

Page 29: End to-end async and await

Agenda

• What is Async?• Why bother?• How does this work?

• Gotchas• Best Practices & More Details• Next Steps

Page 30: End to-end async and await

Gotchas…

• Requirements– You must use the async keyword to await– void events may need marked with async

public void Blah public async Task BlahAsync

• Limitations– You cannot declare ref or out parameters on

an async method

Page 31: End to-end async and await

Gotchas…

• When you can’t await async methods– Inside catch and finally blocks– Inside properties– Inside a lock block– In an unsafe region– Within most portions of a LINQ query

Page 32: End to-end async and await

Gotchas…

• Deadlock and Race conditions, oh my!

var delayTask = DelayAsync();

delayTask.Wait();

Page 33: End to-end async and await

Agenda

• What is Async?• Why bother?• How does this work?• Gotchas

• Best Practices & More Details

• Next Steps

Page 34: End to-end async and await

Best Practices & More Details

• Name async methods BlahBlahAsync

• End to end– Cascading Async

Page 35: End to-end async and await

Best Practices & More Details

• Configuring ASP.NET– Increase App Pool’s queue limit– AsyncTimeout

• Async in ASP.NET page lifecycle events%@Page ... Async=“true” %RegisterAsyncTask(

new PageAsyncTask(GetDataAsync));

http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4

http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45

Page 36: End to-end async and await

Best Practices & More Details

• Unit testing– You can test async methods[TestMethod]

public async Task GivenBlah…() {

var result = await testClass.DoSomethingAsync();

}

– You can mock async method callsmockDownloadContent.Setup(x => x.DoSomethingAsync()) .Returns(Task.FromResult<string>(expectedResult));

Page 37: End to-end async and await

Best Practices & More Details

• Entity Framework 6– ApplicationDbContext

await context.Categories.Include(c =>

c.Products).LoadAsync();int savedCount =

await context.SaveChangesAsync();

– QueryableExtensionsvar employeeCount = await query.CountAsync();var firstEmployee = await query.FirstAsync();

https://entityframework.codeplex.com/wikipage?title=Task-based%20Asynchronous%20Pattern%20support%20in%20EF

Page 38: End to-end async and await

Best Practices & More Details

• Executing tasks in parallelawait Task1Async();await Task2Async();await Task3Async();

await Task.WhenAll(Task1Async(),

Task2Async(),

Task3Async());

Page 39: End to-end async and await

Best Practices & More Details

• Death by a thousand cuts– Batch up async calls

• ConfigureAwait(false)http://msdn.microsoft.com/en-us/magazine/hh456402.aspx

Page 40: End to-end async and await

Best Practices & More Details

• await Task.Yield()http://msdn.microsoft.com/en-us/library/hh873173%28v=vs.110%29.aspx

• Task cancellationhttp://msdn.microsoft.com/en-us/library/jj155759.aspx

• Reporting progresshttp://simonsdotnet.wordpress.com/2013/10/11/updating-your-ui-asynchronously-part-3-reporting-progress/

Page 41: End to-end async and await

Agenda

• What is Async?• Why bother?• How does this work?• Gotchas• Best Practices

• Next Steps

Page 42: End to-end async and await

References

• Asynchronous Programming Patterns– http://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx

• Async and await FAQ• Steven Cleary’s blog• Channel 9• Stephen Toub: The Costs of Async

– http://msdn.microsoft.com/en-us/magazine/hh456402.aspx

Page 43: End to-end async and await

Thank You!