C# Async Programming - Part 3: Demos for Web API and WPF UI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Applause] [Music] [Applause] [Music] okay gentlemen let's get started again please take a seat good let's start into the third hour of async programming now we covered the theory we covered the basics of what tasks are and how async await really works now in the third lesson we are going to do real network programming so we are going to build our own small web server in net 5 and we're going to do bad programming and good programming and then we are going to write a small client app let's use wpf for that and then let's see how we can do bad client programming and good client programming okay let's see how it goes you can follow along if you want we will not write so much code but we'll discuss this code good if you want to follow along please do the following you can save the the code that you have written now but now we will get uh we'll start with a new project here please start a new project but this time we are going to write an asp.net core web application in this course in the upcoming weeks we will spend a lot of time talking about asp.net core web development but today we are only doing a little bit and i will not tell you a lot about what we do just trust me it will work what i will type in so please create a solution wherever you want let's call it async web and then create a project which is called async web dot web server okay this is how it should look like the project name is async web.web server and the solution name is async web put it wherever you want by the way this whole web server programming so the web server part is not part of the first written exam i will not ask you to write a web server in the first written exam that's just a tool that we need for today's exploration of async programming for the first exam you just need essentially to write console apps nothing more good let's hit create let's create whatever an api let's switch to dot net core five let's remove https support we don't need that yet and remove the enable open api support so please here this one is important this one is important and here clear everything to get a really simple project to start yes if i go back the important thing is here that you have to clear this mark here if you clear this one you can enter the solution name here okay if you can't it doesn't matter just create a project did you really choose asp.net core web application [Music] not website web application yeah should be the right one interesting it doesn't matter you can create you can just start two visual studio instances that's fine too yeah good nice again asp.net core 5 api clear all the boxes on the right hand side and click next now create sorry it will only take a few seconds and then we have a very simple web application and we will delete a lot of stuff because it generated a lot of sample code that we absolutely not need before i continue i will wait a few more moments until everybody could successfully create the application by the way the demo that we do here it doesn't matter i called it async web solution name is not relevant you can choose any name that is meaningful for you does anybody need additional time are we all set good now on the right hand side we can delete a lot of stuff please delete the folder controllers we don't need it please delete the weather forecast cs we don't need it please delete the startup method we don't need it the only file that remains is the program.cs program.cs then we can delete a lot of code because we already know that in dot net 5 we don't need all this namespace program main stuff so i ask you to delete everything not the usings keep the musings until host dot create default builder that should remain so your code should look something like this i will give you a moment even that use startup we don't need that the only thing that remains is host dot create default builder configure web host defaults that will give us the most simple web app or web server that i can really think of it just consists of a single line of code and we can now add some functionality here i will wait until everybody could follow along clean up the code currently it does nothing so currently it's not very useful now let's add a little bit of web server code let's say web builder configure app goes to and here we can now write our web server code web builder dot configure app that allows us to add a little bit of code i will tell you more about asp.net in the upcoming weeks for today it's just an exercise just a tool that i need to demonstrate what async programming is all about now let's fill our server with a little bit of a functionality so that will give us a context and then we can just say context.write context.response response right async and here we can say um hello world world come on so question what did i forget we have an async method here what did i forget help me yes exactly let's put a weight in front of it what did i forget now the functionality is called await yes yes exactly exactly because this is our lambda method and that is probably the most simple c sharp web server that i can think of it doesn't get any simpler now we have we really have a web server that's it you can try it you can run your application hopefully if you run it it will come up and fail to start ah no i added weather forecast here no sorry i have to restart it again what did i did what did i do wrong i'm not aware of doing anything wrong oh i'm sorry i'm sorry please here switch from iis express to this one we don't want to use internet information server definitely not we just do console lab programming i'm very sorry i simply forgot that now let's see what i did wrong or whether i did something wrong yes i forgot two lines of code at the end we have to call dot build dot run i didn't start it that's all i didn't start it sorry for that dot build.run and now you see the web server comes up and woohoo we see hello world so now we have a working server we can pass in any url it doesn't matter it will always return hello world always the same got it understand it very very simple what we do here let me quickly describe what the code does it's creating a so-called web host it's creating the web host with the default settings so we don't have to deal with all the configuration stuff and then we tell it that we configure the web server and tell the web server that whenever an http request comes in it should run this method so whenever http request comes in we answer with hello world and then here we build the web server and we start the web server that's all that's very simple in practice you will not write web applications like that asp.net core makes it much more easy if you build more elaborate websites but for now i think it's pretty nice it works pretty well good now let's play a little bit with our web server for instance let's change that code a little bit so that we add here the possibility to come on yes this is correct this is correct and at the end remove the bracket now it should work so what i did i just made this program a block of code so that that we can now add some additional lines of code here so the only thing that i did is i took the lambda method uh as the single line lambda method and told and turned it into a real method with curly braces around it so now i can really write some code okay are we fine fine so far so first let's write some very bad code simulate bad access of eg database thread.sleep thread come on thread here it is dot sleep for let's say 1 000 milliseconds that is a sql query that takes a second to execute and by saying thread dot sleep we are really blocking the web server that is really bad code that is just like calling file dot read all lines instead of file dot read all lines async we should never do any blocking operation not a sleep not a read from database nothing like that always the async possibility understand what i mean this would also be bad task dot delay 1000 dot weight understand what the problem is it blocks the the ui it blocks the thread not a good idea it still works don't get me wrong if i run this application it still works it comes up it takes a second and whenever i refresh the browser it takes a second until our hello world is returned see that but it is not a good idea it's really not a good idea now i thought it would be fun to see whether we can crash my web server you cannot follow along the next step that i do because probably you don't have the tools installed and i'm not sure whether the upcoming demo now works because i've never done it before i just came up with this idea during the break and i would like to try it together with you okay so let's say delay for let's say two seconds you don't need to follow along just take a look at my screen okay let's start the web server i will start it and now it listens it really works it takes two seconds until it answers with hello world and now i have here the apache benchmark tools the ab tools okay apache benchmark is a really nice tool with which you can do load testing so you can specify a url you can specify how many requests you would like to send there and you can specify how many of them should be sent in parallel understand what i mean so what we can do is we can say access localhost 5000 something like this and we can tell it that it should send 100 requests and it should send 10 in parallel so if i run this guy let's see if it works let's see let's wait for a few seconds and now we see it see that one fifty percent of all the requests took two thousand milliseconds that's good a lot of them used approximately two milliseconds but this is really strange you see that one we only waited for two seconds right why did it take four seconds to complete requests that's really strange but this is what you typically see now we could tinker with these values up here and we can increase them until we really crash our web server we can do that but it would take too long to play with it if you would like to do that on your own take a look at apache bench you can simply google it it's a really nice tool if you want to try out your web application maybe you have your own website do you want to load test it try apache bench it really works nicely it's a good open source tool now let's change the web server a little bit change it by removing the weight and add a weight here now this is not the simulation of bad access this is now the simulation of good access because now we are doing async programming no longer waiting good let's run the web server and see if it works and yes it really works nicely you see two seconds so we didn't break any functionality it still answers with hello world now let's try the apache bench as i told you i've not tried this before maybe it will horribly fail then i'm embarrassed but let's try it it will just take a few seconds until we will get back the result hopefully all the requests are successful it should take approximately 20 seconds because we take 22 seconds yes now take a look at this one the demo do worked see the difference previously the longest request took us how long four seconds horribly slow this is a very very simple web server it should be able to handle millions of requests in a rather short time because it does nothing it just waits for 2 seconds and prints a screen sorry princess string in the response and by doing bad blocking access to ui we ruined the performance of our web server a single user would be fine but as soon as we have 10 concurrent users we are already losing a lot of performance because we are doing bad network programming this is what i wanted to show you understand that makes sense or doesn't it make sense and this is why i insist in the rest of this course when you do entity framework and things like that i insist that you do async programming if you read a file access the network access the database and you use synchronous method calls you will get some minus points for your uh from from the achievable points you cannot reach a one anymore it's not possible so remember that async programming and then you do a weight and async and everything is good that was the web server part any questions so far are we fine good so for the next demo please increase this number to 10 000 so 10 seconds 10 000 milliseconds by the way you can write that in a much more much simpler way you can just say time span dot from seconds ten it's much clearer than writing ten thousand because ten thousand what milliseconds nanoseconds seconds minutes that's much clearer just for demo purposes maybe you are not aware of that so now you know it good let's run this guy in the background that's not a problem by the way i started it now without a debugger attached so please run this application by using um debug start without debugging the shortcut the short um the the the keyboard shortcut is control f5 please do not attach the debugger so it should run somewhere here in the background without the debugger and if you are patient enough after 10 seconds it should still say hello world please try that run it without the debugger and it should still say hello world good now for the next demo this will be a client demo we will add another project to the solution so right click on the solution and choose add new project if you don't have a solution just start the second instance of visual studio and create a new project that's fine too okay good add a new project and this time we are going to implement wpf a wpf app dot net core please use net core okay good i will call it async web dot user interface so if you were able to create a solution it should run yeah inside of this folder and async web yes question [Music] could be yeah it could be uh desktop application is it possible with writer to create a windows ui application but we are going to create a windows ui application here now um you can try the same with a console app and if you don't succeed just watch me doing it it's it's not complicated we are not doing wpf currently here okay so i think you will get the the point you will understand the principle async web dot user interface async web.user interface and that will give us a wpf application so now we have the web server here and here we have the wpf application this is not a course about wpf don't get me wrong okay the the point here is i would like to show you how async programming works in a in a user interface application so the focus is async programming not so much ui you can't use anything it this is what i show you this is true for any kind of mobile app for native apps for any kind of ui i just happen to use wpf here because i know it quite well it's really simple so why not using it if you would like to follow along then please open the main window.zan mainwindow.saml and here the first thing that we do is we change the grid to a stack panel yep please change that to a stack panel that should be a stack panel then we are going to define as a text box this one text box we don't need anything inside of this text box and then we create a button and inside of this button we say start web request okay this thing is really ugly so it isn't beautiful what we are creating here that doesn't matter we just need a ui if you want to make it a little bit more beautiful you say here margin 20 and here you say margin equals to 20 again that will give you a little bit of space so if i start my user interface give me a sec of course don't need to ask if i start my user interface here it will give me a ui which will look like this see text box button i can click here type in something i am happy if i make it smaller yeah works as expected could you follow so far any problems good so with that we will add a click handler just type click press enter and then again press enter to create a new handler for this click button and with f12 go to definition you can immediately jump into the c sharp code which was generated and which is executed once the button is clicked okay question of course you just go into the button you type click then it should suggest click just select it and then press enter again and it will generate the code for you see it good are we good now let's write a little bit of code okay using var client equals new http client client dot get async http localhost 5000 this is what we want to access access and then we just say dot result and we store that into a variable var result got it what is this result this result is an http response and we can get the response result dot content dot read as string async dot result and that is my var oh let's sorry rename this variable call it response and the second variable will be result so it should be oops should be like that sorry for using a poor variable name and at the end we say message box i'm still not used to this new keyboard mesh messagebox.show result who thinks this is good code if i ask like that it must be bad code yes it is bad code why is it bad code why shouldn't we program it like that yeah correct it's not asynchron asynchronous uh here we say result and what did i tell you about result it's blocking but still we can give it a try let's see whether it works so i run my wpf application and look what's going to happen do you have a question a problem which problem did you do that one let's give it a try i can type in something i can start the web request and you see now i would like to change the window it doesn't work it's it's frozen i cannot move it it's dead it's really dead for 10 seconds my whole ui is dead until i get the message box hello world so the app works but by using blocking calls my app is dead my customers will immediately call me and ask me whether i'm stupid i cannot give them software which just freezes for 10 seconds until it shows until it displays the result do you get the idea now we see the result of poor programming not on the server side i demonstrated that with the a b tool from apache but on the client side my ui is freezing how can we fix that very simple harry potter programming remove the result remove the result here a weight here a weight because we are having here async methods and what am i missing here async and then well we can change that to task if we want and once we have done that and i run the application oops sorry no we cannot change that to test those that was my um mistake for wpf that's fine if it's void and now see what's going to happen i start the web request but my application keeps it keeps being responsive i can move it i can change it i can type something in here it still works in the background and now i have the result see it this is not parallel programming don't get me wrong this is async programming because we are not calculating things in parallel but we are issuing in this case the get request in the background and this a weight here this one tells c-sharp that here exactly here it can't do anything else that it has to do rendering the screen changing the window size accepting keyboard input and once the get request is done in 10 seconds it will continue the execution exactly here until it gets the next await and it does exactly the same thing here it will give the wpf runtime the control and wpf can do whatever it wants questions does it work good nice [Music] so with these two demos i wanted to make it clear why asynchronous programming is important i wanted to show you how asynchronous programming makes the scalability and the response times of your web servers even for small scenarios even for small web apps significantly better and i wanted to show you how ui applications mobile apps desktop apps no matter what how they can remain responsive even when doing long running i o or network operations and technically what you have to remember is you will you will get back sometimes from certain methods you will get back tasks what you see here and if you get back a task let's take a look at the web server because we have it here too if you get back a task you have to do two things first call a weight use a weight and then add async up here if technically possible the return type of the method should be task only for wpf it's not that easy but that's a detail i will not go into details on that today we will continue with with ui programming later on in this course so that's that's a topic for later good questions did you understand what i told you do you now have a clearer idea what task is why it is important what async await is those of you who are really interested in the technical details it is very interesting to take dot net spy can you remember we had that in one of the last lessons to take dot net spy let it uh regenerate c-sharp from the generated code and then take a look at how they internally implement async await by using a so-called state machine there are very interesting youtube videos out there where people go into the tiny niftiest little pieces of async await and describe you exactly what async await is doing behind the scenes for this course the understanding that you gained today is enough but for those of you who really want to know how it works in background take a look at it it's really interesting if you want to know what happened what's happening behind the scenes um some closing comments for today's lesson lesson async await is it specific to c-sharp or is async await available in other languages too uh-huh which for instance exactly javascript knows async await typescript knows async await it was heavily influenced by the work that c-sharp did c-sharp was the first language to invent async await the guide that i told you about i think last week or the week before anders heilsberg the designer of c-sharp he came up with the design for async await together with his team and guess what anderson spark also influenced typescript and he brought async await to typescript and from typescript it found its way to it found its way to javascript what about other languages what about to be honest i don't know it you can tell me what about java i have no idea i told you i have no idea about java does it support json kuwait are you sure maybe you can google it or maybe maybe you can ask one of your java teachers whether they support ac kuwait or a kotlin or whatever you do what about huh no equivalent okay i see um what about go you told me that you have heard about go does go have async await no they don't they have a very different approach yeah they have so-called go routines and you can do async programming in go using go routines and channels they have created a very very different approach what about rust it's not the same as in c sharp but they have async programming it looks a little bit different than c sharp but the concept is is the same the point that i want to make here is that the knowledge that you gain here the understanding why async programming is important this is universally applicable on any kind of programming language on any stack you will use it in c sharp in c plus plus in java in javascript in go in rust wherever you do your programming the tools are different so some languages support exactly what you are seeing here async await some languages like go for instance have a very different approach but the concept is always the same the problem is universal we have to find a solution for that and every programming language has a solution what about i know that in in nvs network system you're doing angular what about angular does angular make heavy use of async of weight have you ever seen async await in angular you say yes some say no you haven't covered it yet okay the truth is yes you can use async await in angular but you typically don't angular is built on a light on the library which is called rxjs reactive x reactive extensions and reactive extensions rxjs is another different approach from async await to solve the same underlying problem the problem remains the same but the solution is a little bit different so you can ask your your angular teacher when it comes to doing http requests and things like that what how how async await plays in did you do http requests yet so did you do http.get or something like this in angular so this will come a little bit later and then you will see that angular also does async programming but a little bit different um in javascript do we have something like task if we have async await we need to have something like task how is it called in javascript and typescript yeah exactly in javascript and typescript it's called a promise why is it called a promise think of the example that i did with with you with the um looking up license plates in in the parking lot i promise yeah you can think of a promise like i give you a certain job going down there and take a look whether a certain car is standing there and you are giving me a promise that at some point in the future you will have a result for me so they didn't call it task they call it promise the concept is the same question okay okay it's it's very very similar to a task in reality the technical implementation very much differs so javascript works completely different behind the scenes nevertheless conceptually it's very similar do we have any additional questions no then we are done for today uh thank you very much i hope it was interesting i will publish the video especially for those colleagues who are sick today and yeah please take a look at the homework please do the homework please do the multiple choice tests that i gave you and with that we are done for today i say thank you we'll see each other in one week thank you
Info
Channel: Rainer Stropek
Views: 7,694
Rating: undefined out of 5
Keywords: C#, CSharp, .NET, .NET Core, .NET 5, Async Programming, HTL Leonding
Id: By2HlOKIZxs
Channel Id: undefined
Length: 39min 29sec (2369 seconds)
Published: Wed Oct 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.