What are ASYNC and AWAIT in C#? Asynchronous Programming Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up youtube this is dennis bonita for tutorials.eu in this video you are going to learn how to use the keywords async and await in c-sharp they are very important when it comes to multitasking and they are going to be super important for your career if you want to become an advanced c-sharp developer so before we get started with the video please hit that like button it really helps us out and subscribe if you haven't done so already and if you have any ideas then leave them in the comments down below so now let's get started with the course so now let's get started with the content and now let's get started with the tutorial alright so let's look at asynchronous programming normally any code runs straight along with only one thing happening at once line by line if a method calls another method it has to wait for the other method to finish and return and until that happens the entire program is essentially stopped from the perspective of the user even the ui would freeze and look unresponsive until the task is done this is where asynchronous programming comes in handy asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application now when should we make our apps run tasks in parallel well let's look at the following real world scenario from the ms doc so imagine we are cooking breakfast we want to make coffee eggs and bacon with some toast and jam and some juice to wash it all down if we wait for each task to be done in order to move on to the next task it will take let's say around 30 minutes but if you think about it we don't need to wait for the eggs to be done in order to fry the bacon this is a synchronously prepared breakfast as you can see here we can actually speed up the process and optimize it using asynchronous methods so now using the asynchronous method we can first pour the coffee then start with frying the eggs and the bacon as well as well as turning on the toaster at the same time once the toast is done we can put some jam on it then pour the juice and the breakfast is ready so tasks that do not depend on other tasks like frying the eggs and the bacon can be started together tasks that depend on other tasks like putting jam on toast must wait for the toasting step to be done of course don't forget to take off the eggs and bacon so you don't burn them this whole process will take less than 20 minutes thanks to the asynchronous method of preparing breakfast so how can we apply this approach to our programs well asynchronous programming can be achieved in c-sharp using the async and await keywords the async modifier is used to specify that a method lambda expression or anonymous method is asynchronous now when we want to wait for the async task to finish to continue on with the execution of our code we need to await the task using the await operator or keyword so the await operator suspends evaluation of the enclosing async method until the asynchronous operation completes once we are done waiting for an operation to finish we will get the result of the awaitable task for example we can await an async task which will download a text file online and the results of the awaited task will be a string representing the text file actually let's see this example in action where we will be fetching different text files in an async manner alright so in visual studio i have set up a program and let me run it real quick because well it's just going to say hello world so this is a default console application nothing too fancy what i'm more interested in is going to be the following location so now that it's built i can actually move over to the path in the file explorer so i'm going to specifically go to the net 5 debug bin folder inside of my project folder because that's where i want to store my dog file my doc file is just going to be a text file let me check it out here and it's going to look something like this you see the beautiful doge here so that's going to be our doge and i would like to print that dosh onto my screen so in order to do that i first of all need to make sure that i'm using system dot io so the input output namespace which allows me to read files for example okay so that's what we're going to do and then i want to use multi-threading which means i want to do stuff asynchronously and stuff so therefore i'm going to need the tasks namespace here so system threading tasks now let's define a new async method that will await the task of loading a local file so let's go ahead and i'm going to also make it static because i want to load it from the main method i want to call it from there and that's why i need to make it static otherwise i would have to create objects and stuff i don't want to do that so i'm going to add that async keyword here because this is now going to be an asynchronous method and it's going to return a task now i'm going to call this one summon dog locally so it's going to summon our beautiful doge here and i'm just going to write some text saying summoning dog locally dot dot dot so that we know that the next information is going to be in fact my dog and then i want to get the file from my pc so i'm going to use a new string where i'm going to store that data and i'm going to get it from file dot read text so read all text but because i want to do this asynchronously and this task method summon doc locally is going to be async i'm going to use read all text async so a synchronously opens a text file reads all text in the file with a specified encoding and then closes it so that's exactly what i want and what do i want to do it with well with the dog.txt file okay we have this file now this by itself won't work because this needs to be awaited so cannot implicitly convert system threading task string to string because this is just a string now that we're storing it in but we need to make sure that we await it so now we are awaiting this task to be done but we're not blocking the thread for it so that means we are not dropping the main thread and this will load in the background and once it's done it will be stored in this dog text and now i'm just going to display this tag doc text on my console so console.writeline dog summoned locally and here this is going to do the reading for me so since this is an asynchronous method we need to return a task as you can see here and returning a task like this is equivalent to a void method since we are printing the content of the file directly inside the method if we would to actually return the string to the main method then we would return task string so here let's say we were to return this doc text here return dog text like so this wouldn't work because this is a void method now so if i wanted to return the string i would have to add this keyword here maybe not with a capital i but more like this so this would be a way to return the dog text but i'm going to copy this method and get rid of this part because i don't want to actually do it okay so this one here will be our method that returns stuff you saw how it works right and this one is going to be the one that we are actually going to use here all right now that we have our beautiful method here summon dog locally let's actually do it real quick just to see how good our dosh is going to look like and we see we have our beautiful doge that is summoned locally all right so that worked but now let's actually get the data from and a url okay so i want to load the data using an http request so if i want to use http request meaning load data from the internet i need to add this namespace here system.net.http now let's create a method that will get a dog or summon a dog but not locally but actually from a url so let me create a new method here and it's going to be called summon dog from url it's going to be a static async method that returns a task so here let me actually put this into a top line so it's more readable and this is going to be it so static asynctask summon doc from url we're going to pass a url to it and we're going to use this url in order to then load it so first of all i'm going to say what i'm doing and i'm saying i'm submitting a doc from a url then i'm going to create a new http client object inside a using clause this will make sure that the http client object is disposed after we're done with it okay so this is a neat little trick very useful so here using and then in brackets i'm going to say var http client so this will be an http client object so let's go ahead and actually create an http client object like so so now let's close this and actually do the code that we want to do with it i'll run the code so now i'm going to use a similar code to what i did here with the dog text so here let's use a string result that will await for the http client to get me the string asynchronously so now we just need to pass the url like so and then i'm going to just add the right line statement saying that i got my dog so dog summoned from url all right so this is pretty much the task here you could of course also return the result by using the square orders brackets string here as well like we did earlier if you were to do that in my case i'm just going to execute the code straight away onto the console and i'm going to display it so now in the main method let's use those two methods so first of all i'm going to set up a new url it's going to be this url which is basically just the doggo readme file that we prepared and i'm going to use that so let's go ahead and not call this method like we did here because here 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 so you see that was not the best approach i just wanted to show you that and now you will learn how to do it correctly so first of all i'm going to create a list of tasks so i'm going to say i want to have a new list of task objects and here i'm going to create it and this one will be summon dog locally and summon dog from url like so and here some dog from url of course needs to have a url that we pass to it so i'm going to pass my url that we have from here so now that we are using a list of tasks we get into a little problem here because our main method doesn't understand that so we need to make sure that our main method is also going to be returning an async task which means it's not going to return anything but it's going to be an asynchronous method now and it will return a task which basically is like a void method so it's just going to execute some tasks so that doesn't fix the problem entirely because now we also need to await the task dot when all tasks so what does this when all do when all creates a task that will complete when all of the task objects in an innumerable collection have completed so this tasks here is in fact a list of tasks so it is an innumerable and then there was another reason why we get this error and that is because i haven't used this namespace here system collections generic so we need that here in order for this to work now here's some dock locally maybe i should add those brackets in there and now we're going to be able to execute those tasks so now let's go ahead and run this so let's run this code see and you see first we had the doge here it happens instantly once again and then almost instantly and then we got the dog from the internet so from this url so now we have these two beautiful those well one is a doge i believe this one will probably be a german shepherd so now we have those two here and this one was summoned from the url and the tasks were done asynchronously which means they were done in parallel all right so now let's go ahead and also see how long this took and therefore i'm going to use the stopwatch class from the diagnostics namespace so here using system diagnostics and now let's go ahead and define a stopwatch and start that stopwatch just before we start the task so here just after i created this url stuff i'm going to create my stopwatch and i'm going to start this stopwatch so it's going to start counting and then it's going to execute those tasks and now i want to stop the timer and display how much time it took to execute those tasks okay and now let's run this once again with this so we're using the sw and you see this task was done after 0.88 seconds so let me run this again and this will be slightly different you see this time it took 1.66 seconds so this has to do with the speed of the internet connection and so forth so you see this basically just says how long did it take to execute these two tasks because we started stopwatch we stopped the stopwatch and then we display how much time has passed in that stopwatch and this stopwatch by the way is only possible through our diagnostics here alright so this by itself is nice and now you know how to run tasks asynchronously but does it really show us that they are actually run in parallel because it's always that our doge is there before our other dog so what can we do for that in order to test it properly whether they are actually running in parallel because here you could still say hey summon dock locally is run first and then summon dock from url well let's actually test it by just adding a little sleep timer here so i'm just going to say wait for one second inside of my summon dog locally method so i'm going to add this thread sleep and if you want to use the thread class you need to make sure that you have this namespace here system.threading and it's this one here all right now that we have it let's run it again and see if our you see doge was summoned locally slower because we waited for a second so here our other dog was there before and this entire process now took one second and well 60 milliseconds i guess so that should be it right and here once again so it's pretty much always going to be close to this time because it probably takes roughly 50 milliseconds to load the dosh into our console application and the other process by that time is already done so now we are doing both processes in parallel which is pretty cool so you see this is pretty much how you can build your asynchronous code and you can build your projects now of course this was a super simple example we were just loading data either from a file or from the internet but if we were to use a more complex example it would still work the concept is always the same add async task and if you need to return something add this less than sign then the data type that you want to return and greater than sign and then of course make sure that you return this type of data in any of the outcomes of your code here all right now you are pretty much ready to program asynchronously thanks a lot for watching this video i hope you enjoyed it now you know how to use async and the weight in c sharp and if you like that video please hit that like button and subscribe if you haven't subscribed already and also i have a little challenge for you what you should try to do now is to write the program that we wrote with a synchronous approach and then use the stopwatch class in order to compare how much time each of them took and also share that in the comments down below so the comparison between doing it asynchronously so multitasking and synchronously so single tasking alright so good luck with that challenge and i hope to see you in the next video
Info
Channel: tutorialsEU
Views: 4,072
Rating: undefined out of 5
Keywords: Tutorials, Tutorial, Programming, Course, programmer, difference between async and await in c#, what is asynchronous programming in c#, asyncawait c# explained, async and await in c# tutorialspoint, how async await works c#; when to use async await c#, asyncawait c# in depth, async without await c#, async await tutorial c#, async explained c#, await explained, c# task async await tutorial, denis panjuta
Id: 5a6WCBftjvw
Channel Id: undefined
Length: 18min 34sec (1114 seconds)
Published: Fri Jul 23 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.