Async/Await in C# - How it works and how to use it

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome to code porn the show that has nothing to do with porn and everything to do with code in this episode we're going to look at the async await keywords and examine what it does under the covers the problem with asynchronous code is that it can be significantly more complex to use and write than synchronous code especially if you need to coordinate many related operations and deal with errors and this is why most developers choose less efficient synchronous alternatives to writing async code but the main new feature in c-sharp 5 is language level support for implementing asynchronous methods we get this - the async and await keywords which makes it possible to write and use asynchronous code or retaining most of the simplicity of simpler synchronous code the async keyword gets added to a methods declaration this tells a compiler that we want to use asynchronous features inside of this method the async keyword does not change the method signature though it doesn't change how the method is used only how it's compiled this means it can't be used to overload a method for example these two methods are identical even though one has async applied to it and the other does not a sync simply declares that we intend to use the await keyword but we aren't bound by law to actually do so as we'll see using or not using a weight will make a big difference in how our code looks and works post compile applying the async keyword to a method does not actually make it asynchronous actually quite the contrary our method will still execute in a synchronous manner but that doesn't mean that using the async keyword doesn't have an impact on our code let's look at this example console application in the main method we're newing up an instance of our worker class that does some expensive work that needs to get done while the user waits we use a while loop to give an indication to the user that we're still waiting for the work to complete our worker class has two methods do work to invoke the work a long operation which just pretends to do something useful we want to run this we won't actually see any progress indicators because our long operation is synchronous which means it will block until it's done let's add the async keyword to our do work method and see what happens it actually does the same thing it did without the async keyword in reality though our code is changed during compilation let's take a look at what happened to it I'm using il spy to decompile our assembly to actually see what async and await translate to I've gone ahead and disabled the decompile async methods option inside of il spy otherwise you would only really see the async and await keywords as we've written them in our code which won't be very useful for this demonstration first off notice that we have a new class that we didn't write the way a scene gets converted into asynchronous code is by building and using a state machine this class is the state machine for the work we want to do except for the do work method which is the method we marked with async everything else is the same just as we wrote it but the do work method has been changed and it doesn't look like anything that we wrote it starts off by setting up a new instance of the state machine and then stores a reference to the instance of our class that's currently executing next a new async void method builder is created this is used to schedule and kick off the state machine then it sets an initial state up for the state machine to negative one from there we kick off the work using the async void method builder using the start method and passing in a reference to the state machine instance if we follow through we get to a point where it actually kicks off our state machine to do work by invoking the move next method on our state machine now if you look close to this method you'll notice that it's actually taking care of context switching for us this means we don't have to worry about moving from one thread to another when we're using the async and await keywords the move next method on our state machine is actually what we're interested in because that's where the method body from our do work method was actually moved to to sum this up there's a check on the current state if it's good to go then our original code is executed we said is completed to false write a message to the console and then using the instance of our worker class we invoke the long operation method when it's done we write another message to the console and then set is completed to true now as we saw when we execute at the demo there's nothing asynchronous about this code not yet anyway let's go back to our example application and apply in a weight to the long operation method invocation now that we've applied the await to this method invocation the method body up to this point will execute as normal and then the long operation will execute asynchronously and the rest of our application will continue executing when the long operation is done executing whatever it needs to do the remainder of the do work method body will then execute because we can't await a void method we need long operation to return a task so we'll just wrap our logic and a task start it and then return it now when we run this code we see our pacifier working away until the operation has completed now we're running asynchronously but what's change in our code back and I'll aspire we now see two additional properties on the state machine class an object called stack and a task a waiter the only other difference is in our move next method which has gotten a bit more complex now it's using an a waiter that is retrieved from our task returned by the long operation method if it hasn't yet completed then it sets the state to zero copies the instance of the await ER and then subscribes to the await unsafe on completed event which schedules a state machine to proceed to the next action when the specified a waiter completes when this happens will reenter this method and then since the state is now zero we'll hit the else statement to do some cleanup after that it finishes executing the rest of our original code so now that we've gone and had a look at what happens under the covers hopefully it's clear that asynchronous code doesn't come for free there is a cost associated with the async and await keywords which should be considered before just slapping them on any old method that just happens to be running slowly just because you can doesn't mean that you should alright well that's it for this episode be sure to subscribe to our channel follow us on Twitter and Facebook and visit code born calm and you have nothing better to do see you next time
Info
Channel: Code Insights
Views: 141,680
Rating: 4.8000002 out of 5
Keywords: how to use async await, async/await, async await, c0deporn, c#, .net, asynchronous, code, programming, microsoft, c# tutorial, c# 5.0, c# 6.0, c# 5.0 features, c# 5.0 async, c# 5.0 async example, c# 5.0 await feature, c# 5.0 async await example, c# async keyword, c# async await, c# async await explained, visual studio, .NET Framework, Software (Industry), Asynchronous I/O, C# (Programming Language), dustin davis, codeporn, jon skeet c#, c# async await update ui
Id: 6_GTdR0gBVE
Channel Id: undefined
Length: 6min 22sec (382 seconds)
Published: Sun Jun 02 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.