YTread Logo
YTread Logo

C# Async / Await - Make your app more responsive and faster with asynchronous programming

Jun 09, 2021
Have you ever tried to get into

async

hronous

programming

and already got stuck on all the complicated keywords or maybe you discovered that while it sounded great, you just couldn't get it to work well in the real world in this video I'm going to show you ? I will teach you how to

make

use of a singer's

programming

with very little effort. My name is Tim Quarry and my goal is to teach developers how to learn C-Sharp the easy way in this video. That means I'll skip the whole threading story. it may get some people in, but it's not really relevant to what you need to know today.
c async await   make your app more responsive and faster with asynchronous programming
What you need to know is how to use

async

and

await

in the real world to

make

your

applications

faster

and

more

responsive

Now just to be clear on what we're talking about, let's review what I mean by synchronous versus

asynchronous

programming : The work that is done in sequence is task A, then task B, then task C, and finally task D. The problem is that no one else can do any work. until task D is completed,

asynchronous

programming allows us to fix that problem, there are two big benefits here SC right away when you use it, the first big benefit is in its UI, if task B takes a long time, that will block Your UI execute a task asynchronously while you can return its full form and control to the UI to keep it

responsive

.
c async await   make your app more responsive and faster with asynchronous programming

More Interesting Facts About,

c async await make your app more responsive and faster with asynchronous programming...

The second benefit comes into play, especially when tasks C and D do not depend on task B; in fact, perhaps none of the tasks depend on each other. otherwise they may just be things that need to be done, we don't need to fetch data, in that case we can run them in parallel, that means as long as

your

system has the resources it will try to do all four tasks at the same time. once, if each task took three seconds to execute instead of taking a total of 12 seconds to complete, it might take only four seconds.
c async await   make your app more responsive and faster with asynchronous programming
Hopefully at least now you understand what we're talking about. I think I'll make it even clearer if we look. the code before doing just as a reminder, it would be great if you like this video and also make sure you are subscribed to the channel. Okay, let's move on to Visual Studio as you can see. I already have a demo. I set up the app, rolled it up, put together some basic code that I needed to run the demo, but that didn't really apply to what we're talking about. I'll give you a quick run three before we get started, so that's up to the UPF app. you just have a form here for the UI, you have a couple of basic things, you have two buttons and you have this results panel down here, you might see the results panel, but that's here, it's called the results window, so What we're going to do is run a task the way you normally would using this button and see the results down here and we'll see that the UI crashes and it takes a little bit of time and it's a waste to display the information in the screen and then what we're going to do is where I use this button here, asynchronous execution to allow us to do the same task but asynchronously and we'll see how I can still use the UI and how you can even See the answers come in a line at a time and they are set all at once at the end like it's not normalized and we'll get to all of that in a moment, but that's our basic demo UI, now just a quick disclaimer here.
c async await   make your app more responsive and faster with asynchronous programming
This is a DPF application and I am not using mvvm. I normally use mvvm with any kind of real WPF application, but in this case it's just a demo. The other thing to note is that I don't really like the idea of ​​putting code behind your UI and the reason is because when that code says it can't be used, if you go to a different UI you get No I can pull it out and throw it away and it just makes a mess, so I really recommend it. you don't put code in the code behind except what is necessary to get data off the screen and off the screen, but in this case again, since there is a demo, I put all my code in the code behind that I just can't figure out.
Don't do this yourself for a real application, it's just a demo, okay, so the code behind here. I already have a few things set up first. I have to click the buttons on the events, run sync, click which one is this one here and then the run async, click which one is there, so run async is blank on this moment run sync has some code and what this code does is the following: first we have the timer to start again and this is how I'm doing it. I'm timing how long this takes, so the way to do it is to start this timer.
Now you don't want to use a date/time point and try to catch that it's not as precise, this is much

more

precise or you start a stopwatch and then at the end we stop it and so everything in between is timed and we'll say that okay, here are the milliseconds elapsed between this line here and this line here which, in theory, will record how long it lasts. so there's an even more precise way to do things if you really want to dig into tracking your performance, but this is a really good performance counter for you, you know general stuff, so that's what we're going to do.
This timer will start, it is built into the dotnet framework so you don't need any special libraries. Just run this line of code here that says start new, then run your code and it usually stops and takes the elapsed milliseconds, so that's it. all we're doing here and the last thing we do is write to the results window a line that says here's a total execution time for that action, so in the middle there's this action called run asynchronous download. Sorry, run download. sync so let's see what it does we go down here run download sync says first give me the staging data which is just a list of strings from a bunch of websites Yahoo Google Microsoft CNN Stack Overflow Code Project so just a list string which it receives and also clears the results of Windows Start, so once it gets the preparation data, it loops through each website and calls this download website and passes the URL of the website so that the download website simply creates a new web client again integrated into network material and then downloads a string representing the entire index page.
Now the reason I'm using this is because it's a great simulator of us requesting data and waiting for it to be done, some websites are quite responsive. kind of not so much now, the other note here is that I'm actually building a website model. I call it output where I put the URL of the website that we loaded and then the actual data that we got as well. I returned that set of diameters and there is that model. Right there, the website URL data is pretty simple, just two properties, so the reason I do that is so I can keep the information together, the actual website URL and then the actual data for this site .
Now I don't actually use data that I just use. the length of the data to show me how big the website was in terms of characters okay so make a backup here we run download sync so run download sync download each website and when it's done, it will report the website information and pass the result. is the data model of the website, what it does is it simply writes to the text in the results window, it adds the URL and the length of the data and at the end it writes a new line, then we have one entry per line, so that's all we have.
What we are doing is simply taking a bunch of URLs once we download them and reporting the information to the screen. That's something important. We download a website, enter its port ID. I think of the following website and we download it. and report it, so let's see how it actually works now, just know that the first time you run this it's a lot slower than the second time and that's because it actually exits and tries to find the proxy settings the first time after that or the members. until the app closes, so the second and third time is much

faster

, but I will ask you the first time and I want that the first time I have to observe two things, first of all, I will try to move the window after clicking this . button and it won't move and secondly I want you to see if those lines appear one at a time or all at once at the end okay so here we go click the button try to move it nothing happens and there boom. those lines appeared all at once until I saw the merge time, this is in milliseconds, so it's two point two seconds, so there are the websites, how long did they last, notice that if you run a second time, it changes, You know, one point two seconds even. just 0.7 seconds, so it gets pretty fast once you get past that looking for the proxy server, but that's where we're about three cables of a second to download these six websites, so let's see if we can.
I don't do anything with these two problems. Problem one. I can't move the window while it is running. Problem two is that they appear all at once at the end instead of one at a time as we retrieve the data. So let's address it. Problem one first because I'm going to show you that there are two different parts to async and I'm going to make sure to separate them into their respective parts, so first let's essentially make a copy of everything that happens in run sync, click and copy this. everything and I'll paste it here. The only thing I will change is that we will run the download asynchronously.
Now it doesn't exist yet, but we'll create it, so let's minimize some of the other things we don't do. It's not necessary and we won't actually copy this again, run download sync and I'll just paste it here and say async ok, so we'll have exactly the same thing as before, if we were to run this, it would run the same way both times. but let's see if we can get this to work synchronously so we can free up that UI and it won't crash while it's running. If you know anything about the website download method, you will know that down here there is actually, wow, it's not a download website, here we go here, the download string for the web client, it's actually a download string asynchronous or asynchronous task, we're not actually going to use that yet, we're going to wait.
I'm going to demonstrate how to do it. If you can't change that, because sometimes you have a lot of people's code or Cody just can't touch it, but you want it to run asynchronously, and then how do you do that? So, I'll go ahead and do it. For you, I'm just going to show you what you can do to make this work a little bit better, a little bit of synchronized rest, so what we're going to do is take this line here where it says let's minimize this, let's not get confused. line here with the download website and then pass the site.
Let's say we have no control over that, but we want to make it asynchronous, so the way we're going to do it is here, sa task dot run and what tasks. that execution says: I want you to sit down, execute this here inside my parents. I want you to run it asynchronously. Now what we're going to do is go through open, closed, another set of prints, so notice open here, open, close, and then. we're ready, let's make a lambda expression to make it equal to greater then and say, okay, pass this code right here to run it as our task, right now, right now it's screaming at me not to panic since I'm saying that the task surpassed knows what. was going to return is actually a website data model type task, okay, that's this right here, that's the return, so if they return a ml website task, not a website data model , which is what we expect, so what I've done here is I've wrapped this code in an asynchronous bubble but now I want to use what's called the

await

keyword.
Now what a peso does is okay you need to run this asynchronously but you have to wait okay and the reason I want to wait is because I need to have these results so I can report on them so I can't continue reporting on them. something I don't know the results of yet, so we have a heavy keyword now it still screams Yo, but the reason it now is because it says you can't have a waitless operator unless it's an asynchronous method, we change that if it says asic above, yes everything is fine, now here is a tip right away and don't worry.
When starting out, he got a little lost. Let's go over all of this again, but first I want to get it all out here, so a very important tip here don't return void from an asynchronous method if you have nothing to do. return don't create something just say tasks okay now if you have something to return say it was actually spinning a string what you do is you just say tasks of type string and now that says this will return a string so return , yes or whatever. and that works now, these return chains don't, don't worry about the setting and the tasks that take care of thisasynchronous, but in our case we don't have a return type, it was returning null, so now we just say return tasks, okay, so do it. sure it doesn't return empty now there's an exception and we'll see that it sends it but there's no hood event you can't change an event from empty to task it doesn't work that way so you have to leave it empty and that's ok ok , that's the only exception that c-sharp knows about and that's fine, so let's go back and look at our asynchronous download run and see what changes we made first.
We made it an asynchronous method and then said it had to return a task type. Now there's one more thing that I didn't point out, but it's actually a very important convention that you really need to follow and that is that you always add async. to any method that returns asynchronously now in our case we had synchronization so async may not make sense but the reality is normally run the download and run the download async so just make sure you add async at the end. just everyone know that this is actually an asynchronous method not an rs1 sync so we have an asynchronous return of task type not void type and we have the awake keyword here and again a weighty keyword says run this asynchronously but wait for the results.
You might be wondering why you would do that because it seems like if you want to run something asynchronously you shouldn't wait. That makes no sense. Remember our example of ABCD tasks. You know if we're waiting. task B before doing C and D, what's the point when I just do a sync and the point is that any caller can continue with the job from it after calling this? Well, at least our UI can do the UI again. works while this is running, even while we're waiting for it, so it gets in queues, okay, we're waiting for this, it's not finished yet, so go ahead and do your job and then it says oh you.
I know what I got, the results I'll go ahead and process them from here, which allows us to have a little bit of flexibility and a little bit of control because it runs asynchronously, so all they did was wrap our call to the download website in a run task that was running I had the lambda expression pair pair open and closed the actual command for which we called it wrap everything in pairs for a task that is running okay let's see what the difference is then I remember this is run asynchronously inside our run asynchronous, click ok, this right here warns me, it says, hey, you're not expecting anything here, so it's going to continue later.
I'll leave it for now, but I want to show you what happens, but we'll see. Let's go back to that warning and fix it, but for now let's go ahead and run this. First I'm going to fix my async. We remember that it takes a little longer the first time, so I want to have it linked. I'll show you. I can still move the window, so let's click here and now I can move around and see that they're showing up and I can move my stuff at the same time, but I want you to notice something else right here. total execution time too and after that I have six websites that have been downloaded so it's a bit strange because it stops my timer before all this work is done.
I'll show you why, because we never said to wait for this, so we did it, so he said okay. it's a shot and forget it call it we're not worried about it so I continue where I stop the stopwatch we're on it gives us a lap in milliseconds where I write that out the window and we're all ready to go and this is where people usually panic and say oh no I've broken async/await I don't know how it will work, it doesn't work for my app because I can't just fire it, forget this stuff so what's going to happen?
Well, don't worry, okay, let's fix this, all I'm going to do is say, oh wait, it's real, hold this now, don't forget whatever you do, hold on, you have to sync now. I'm not going to change the method name here and I'm not going to change this void thing. The reason is that this is an event, therefore I don't change it from void and I don't change the event name because it would break the event. I could go ahead and click on async, but it's an event, so let's leave it alone, okay, let's try this again and say run async, move it, okay, enter it one at a time, there we go, now let's run both. again just to see the time difference so run i sync again that's 13 64 8 33 1193 854 some out there run normally per second 710 seconds 1.1 seconds 0.9 seconds both run at about the same speed okay so Let's see if we can't.
Modify them a little so that they run at different speeds, so let's take advantage of this parallel execution now. The reason they run at the same time or at the same speed is because of this right here through weight. What we are doing is calling. a first website that says to download that, but wait, well, that's what it does: it blocks this particular method from going to the next website until the first one is downloaded and then it moves on to the next one and blocks itself until it's downloaded. download the next one. so let's solve this by copying this method and we will create a new version mmm eyes, we will call this run asynchronous parallel download, so it will do all these tasks in parallel instead of in sequence and independently each one. one okay, so let's create a website data model type task list, okay and we'll call these tasks, that's it, it's a pretty complicated list, let's look at it, in the center we have this website data model. and that's what this download website returns, but remember if you don't expect it, it returns a website data model type task, which is this right here and I'm talking about a list of them because I have a list of sites website that I want to download, so now let's delete this line here where your report on something and we'll get rid of a burden and now we have this where it becomes a website data model task.
We have this list of tasks and data from the website. model, so it's going to say tasks right here, tasks, period, add and add that task, so what this is, it says I have this little bit of work, it's kind of a bubble of work that I'm going to do or I'm going to I'm trying to do what I'm working on but it's not finished yet so I'm going to put this in a list so now list these little bubbles of work these little pieces and they all run at the same time and then at the end of this I go to have this list of all these sets of tasks that are running or have completed well, so what we're going to do down here is save our results, it's equal to a weight task point when everything, so what does it say when everything ?
I'm going to pass some tasks, a whole set of them, whether it's one or a hundred, and just wait until they're all done and when they're all done, I want you to pass those results back to these results. variable so that that results variable is actually an array of the website's data model. Now I'm more of a fan of a list instead of an array, that's not a big deal because for each one still works on it, I'll say for each one for each element. in the results and what is the element dot element, there is the website data and the URL, so now I can use that method.
We have report website information, so I can take a copy of that and come over here and say report item website information so you can see. the difference here before here we say do this task and wait and then do the next task and wait which one works and is asynchronous which allows the UI to take back control and allows us to display that line one at a time instead of all at once, but it still means that we are waiting for the duration of some of the download times so you know if each one of them takes three seconds and there are six, it's 18 seconds where the download time, while here or do I mean, okay, I have a list, I want you to download it next, download it, the next one, download it now, all they're doing is picking up that task and saying here's this little work bubble, it's already refusing to download that website . just grab it and we'll put those work bubbles into this task list and then we'll say you know what, when they're all done, take the results of all of them, review them and report back, then what's going to happen?
The thing to do is wait to show it to us until they're done, but they'll ask you much quicker. Okay, so you're missing out a bit on the negative method and there is actually a way to have the best of both. worlds, but that's for the next asynchronous video I do, where you do some more advanced things, like reporting from an asynchronous method in your UI, which might be a little complicated, but we'll break it down, but that's not in this video. so you should know that for this we're going to lose some of our one at a time by showing it a little bit, but we're going to gain some speed by doing all of this at once, so let's change our call here in our event. run async from run download async to run download parallel async and let's run this again and we'll do the normal thing of execution, remember this is slow at 789 let's do it again 385 379 293 373 let's do normal 792 11 hundred thousand 800 793 asynchronous - 47 to 52 - 41 so you can see the difference, now we have that speed increase because each of these websites is downloading at the same time, that means that generally we are waiting for the longest website to download the slowest one, so an Omega that was quite large is two hundred and nineteen thousand characters.
Stack Overflow has 256k, so one of these two is probably the one we're waiting for, so these others may have ended up parked there, just waiting until you know they're coming back and once you know they're both coming back, then everything will be ready versus all the weights for this whole thing. to finish then you move on to the next one and that is the next one the next the next you if you had done all this before finishing everything that is why the normal execution time takes eleven 100 milliseconds versus half that time or minus a third of that time, as you can see, there is a big difference right away in my application, so let's recap what we have learned so far, first of all, the basic keyword here, many, that we deal with are sink and a weight a sink marks a method to say this is an asynchronous applicator or an asynchronous method and oh, wait is what we use to say wait on something, wait on some kind of asynchronous method and the reason we use that wait is because if Yes we don't, we'll fire, forget about it and move on to the next step, which is what we had when we saw the timer was written first and the timer continued while the websites were downloading, so it had to say No, wait for that, but even though we're waiting for something, it still gives control back to the UI so we can move it around, we can see other things pop up, other things might happen, in fact we can even start other events. or other tasks performed by the user while waiting for it to complete, so it really makes a lot more use of your operating system, a lot more use of your computer hardware because we can do a lot of work and still still give users the experience of a responsive application.
Nobody wants to have an app where they can't touch anything. Something is running. You know, I just get stuck. It may even turn gray. hourglass, some like that just aren't fun, so this way just saying a sink in a weight allows us to avoid that, but we also have the idea of ​​parallel running where we're doing multiple tasks and then saying hello when they're all done , then it goes on and on, in this case, a weight for all of these and then prints the results. Now, the only thing I mentioned before that I didn't make it up, but I'll show you how you can do it when you can.
I'm not touching a method, this execution of tas is a task that overrides a call to make it asynchronous when it's not, but in this case we have the option down here in the download chain to change that to an asynchronous call, so Lo What I can do is change that, let's copy and paste and this time I'll say download asynchronous website and I'll make this call right here download string to download string asynchronous task and I'll wait for it and finally I'll be able to make this method asynchronous and return a task of type model of website data, don't forget to change it to task and why task, remember when we go back to an asynchronous method, but just say "continue, we want to have that whole bubble." I'm saying I've got this, it's working, it's running and I'm moving on.
I'm holding on to it so that later when it's ready I can do something with it and that's what we have to do, make it a task, make it a task. of type website data model, so I'm using the built-in one and they gave me asynchronous tasks, so that's great, all thatneed to do is come up here to run the download in parallel and change this to instead of running tasks. I can just take it out and say this is downloading the website or downloading the website asynchronous, that's it, since it's already asynchronous, now I have to do that task, execute things, I need to pass that to my list so that it works the same way we run asynchronous. boom run you know it still works like before just I don't have to do that task that runs so if you have control over the method and can make it asynchronous natively that's great and go ahead and do it but if Don't despair, you can just wrap it in a task point run and then you'll be good to go, so it's a bit more of a complicated topic in some ways just because you have to think about what's going on and plan for what you already know. .
I need to make this asynchronous, don't you make the next level go up asynchronous? async method let me make the method asynchronous, you need to change it from any output to an output task of that help that type, so that the task is only if you are returning a void or a task chain task from your model, whatever, those are the big things to remember when it comes to synchronous and then you want to wait for something or not wait for something you don't have to wait for something but just rememberIf you don't know, wait, wait, first it will return a task type or any result you want and secondly it will allow your code to continue just like it did with our stopwatch, they continued, they stopped and K is the elapsed milliseconds of two milliseconds, which sounds great except for the fact that it's not actually the time it took, but the time it took to say goodbye and move on, so when to use a weight is when you need to trust the data to arrive. rollback or use that data to return or your application should not continue until you have that data, that's when it usually waits, so async await we have tasks and that's it for asynchronous programming, it really is that easy, no need to worry . apartment models or you know, threading contacts and changing contacts, all the other things that we used to deal with, many of which are wrapped up in just a sink, a weight and chores, those three things, so if you see some examples online where you use this, those more complicated things don't worry too much, that's hidden behind the scenes using this just as a sink somehow.
I hope you found this valuable as I said there is a part 2 on the way which will be the more advanced things like canceling a task mid tasks and also retrieving some information from the task once it is running so some updates to status are that kind of thing, so in the meantime I'll have that more advanced video for you in the future. I would love for you to leave a comment. below and let me know what you think, if you have any questions that you would like answered in that second video, if it's not available yet, but I see this, go ahead and leave them in the comments below as well and I.
I'll try to go back to those and answer them in the next video. Also in the description there is a link to my mailing list if I let you know about some of my paid courses and the discounts the only people on the mailing list get. Definitely go ahead and join the mailing list. Thank you very much and I'll see you later.

If you have any copyright issue, please Contact