Learn C# with CSharpFritz - Async, await, and Multi-threaded code

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Music] [Music] [Music] [Music] [Music] [Music] huh did we get the transition right this time hey there it is good morning good afternoon good evening whatever time it might be where you are out there welcome back to the live stream my name is jeff fritz and this is learn c sharp with c sharp fritz how you doing there this is of course a session this is a a very much scripted session with ama capabilities ask me anything you'd like about c sharp where we're going to learn more about c sharp we're going to learn more about the programming language and hopefully get you some answers and and get some discussion around some features some things that are going to hopefully make you make you a better developer thank you so much friends for dialing in i'm i'm seeing all the folks over here in the chat room let me bring up the chat rooms they're over here it's a full house over on the chat room today oh my goodness look at all these folks um because we're broadcasting to learn tv youtube and twitch so if you're watching on any of those services um it's so good to see you thank you folks from youtube and twitch will answer your questions right here in the chat room let me say hello to some of the folks that are here my goodness look at them all look at all the chat i'm going to start over here on youtube and i'm going to start with greg cyrus good to see you dj curry synth howdy howdy christian rodriguez hello to you daniel case has dialed in from essex in the uk nika hello hello carlos good morning to you mahalos uh is this streaming on twitch as well yes and i shared a link there you go uh i'll be hacked hello good to see you cassoon welcome uh is that is that dooch duke hello hello um [Music] let me see here uh yeah let's do this uh moosie moosie from india ladybug good to have you back here let me say hello to some of the folks over on twitch chris jones is here how's it going um krypto yani hello good morning good afternoon eggsy's here how's it going um scrolling through here flying russellini beaujon is here uh i hope everybody's having a great day uh hola toni uh from nigeria welcome in just ray is a fish i thought you were just ray though but you're a fish mr joe b how's it going get got your coffee ready for another c-sharp session great to see you mr joe b hello you like the hat you like the xbox hat right i'm i'm staying i'm staying in microsoft theme here it's not explicitly visual studio or c-sharp or windows it's xbox today right like gotta bounce around to different different things i've been looking for a big hat i haven't found need to find a bing hat there's gotta be somebody's gotta have a big hat uh you like the shirt yeah nasa shirt today hello to kevin in the dominican republic good to see you uh bow bow is it bow look tongue good evening to you um let me see here serge serge dev is here zofran 777 where can you find info and setting up using the notebooks it's all right in the github repository if you head out to github.com c sharp fritz slash c sharp with c sharp fritz if you're watching on youtube the link is in the description just below there it is in chat for anybody that's going through and and uh following from there uh jfray hello to you in switzerland richard is here hello uh yeah the whole world is here my goodness oxtary in cyprus rupesh in nepal my goodness it is so good to see everybody uh is that it egiba from senegal let me know nikhil in india hello gregory white in ireland there we go we got an irish irish fella in here carlos barbosa grabbing a coffee um marcus in sweden i think i mentioned that jfray uh john i'm not sure how to pronounce the rest of your handle there hello to you in connecticut um okay that's a fine factoid about aws there thanks so much um tron is here from it from vietnam it tran is that uh i think it's usually pronounced tran isn't it let me know uh marius thank you for the great c sharp lessons thank you for tuning in appreciate everybody who tunes in and is watching narulou lee loy from vietnam is here uh would a duck duck hat be close enough um see it's a branding thing i can't quite do that burger b hello hello uh let's see uh lurchikus from florida hello cigar uh muhammad you should i should google for a bing hat i see what you did there i see what you did there muhammad uh chaitanya hello uh auto microsoft nasa acquisition league it doesn't work like that it doesn't work like that fernando in brazil hello um tama hawk i see you're doing something there your visual studio 2019 is not stable often crashes uh do a repair on that you something else is going on there um on your machine how are you doing there otto rwp one bite from indonesia um a couple folks from india chaitanya starfish blast 1967 from germany do i wear these glasses the whole day i wear them a lot of the day when i'm when i'm uh working on them on uh on a computer these are gunnard glasses they're designed to help with blocking blue light and keeping my eyes from getting tired from it um when i was on the hello world show you've seen the hello world show it's over there on learn tv uh and you can find the hello world episode that i was on um it's over on youtube uh when i was on last week i didn't wear the i didn't wear the glasses all day i had i had been busy tuesday evening and i did right through into the evening went downstairs to get dinner realized this still had them on took them off and left them in the kitchen and the next day i completely forgot about them i got done that hello world show and i had a headache like you wouldn't believe so i found that these are for me very helpful um poncho hello from to you in the netherlands i like what you did there the task from result i didn't write any samples with the from results stuff might need to cover that um favorite design patterns love the repository pattern there nick um s z z b d d good morning to you in michigan pedro is in brazil you learned and used mutex not gonna be used talking on mutexes and some of those other multi-threaded helpers we're just going to be talking about async await task and we're going to get into parallel for each today uh nurse in kazakhstan do i plan an advanced course advanced dissolve is is certainly a question um i think there's an opportunity to bring on some of the c-sharp team members and and go a little bit deeper on some of the topics it's not a bad idea let me think about it nikhil good morning to you in india actually it's probably good evening to you um aquarist 123 in england hello to you farad in the ukraine what's the twitch url twitch tv slash visual studio uh jack is in turkey uh is it is it clincy in kosovo uh mark hello to you in russia another senegalese oh my goodness so many folks today this is great um just ray asks is async await a programming style that makes use of multi-threading more efficiently yes and we're going to talk about that we're going to see some concrete examples here miss 101 3374 because 101 3373 and earlier they were all taken greetings to you in germany hello hello harvey's in clearwater sammy's in tunisia working in tunisia working in germany oh my goodness um what time are we starting we're gonna get started here in just a minute i want to make sure i welcome everybody and say hello um it's the least i could do to help out with folks over here that are acknowledging you and welcoming you in because it's important to me that you know i'm reading every chat message i i want you to know that this isn't just a presentation if you want to watch a presentation you want to learn some of these topics sure go out search for the youtube video you can watch it and in 15 minutes you're going to learn all of c sharp in 15 minutes right this is about the discussion this is about getting involved in helping you out that's watching out there at home or in your office or wherever you might be if you're watching the recording i hope you pick up and i hope some of the questions asked by the folks in chat that we get to today apply to your scenario whatever it might be and and we go through and we answer and work with your type of scenario of course i'm going to review questions that come in comments that are just below the youtube video on the recording if you are watching this recorded sometime in the future and if it is the future when you're watching this hello future people so good to see you um let me know who wins the super bowl so i can place a bet on it and we'll do this whole back in time thing and maybe we'll win a couple bucks does that work like that i saw that in a movie once let me know um owner good uh hello to you in turkey uh update to the 2022 preview yeah visual studio 2022 is coming soon in case you missed it visual studio 2022 we announced that it's going to be released there will be a release event that you can tune into on monday november 8th um it'll be it'll be on visualstudio.com i think that's where they're broadcasting it um but it's the same week as dot net conf so the 8th you're going to be able to see the launch of visual studio 2022 one day later you'll see the launch of dot net 6 and dot net conf 80 sessions for dot net conf um bro broadcast and brought to you from folks all around the world six of the seven continents represented sorry antarctica and folks talking about all kinds of different.net topics i hope you tune in netconf is november 9th through the 11th including 24 hours straight from the 10th through to the 11th actually 32 hours straight because we start at i think it's 9am or yeah 9am pacific time on the 10th and we go right through to 5pm pacific time on the 11th there'll be something broadcast from somebody from your part of the world in your time zone so i hope you tune in it's a really great event that we really enjoy um you're having headaches with too much screen time burger b says over there on twitch i gotta catch up here uh chai tiana asks am i done migrating to ravendb i ran into a couple of data consistency issues my data types weren't all the same i had date times in a field and sometimes they were date time offsets and it was getting confused when i was building indexes and some of my data wasn't quite accurate there so i had to go through an update um a couple million records appropriately and that took a really long time i think i'm there with my migration i'll let you know um before tomorrow's stream advanced course and how to team task creation options yeah there's there's some deeper content there that that we're not going to get into today but we definitely should talk about am i going to be covering cases for configurate false yes that is something that we get a lot of questions about i'm going to cover it briefly because quite frankly for beginners you shouldn't be calling configure await false period you shouldn't be doing that let the framework figure it out and i'm going to show you exactly how it works why you would want to call configure wait why you wouldn't want to call configure wait we're going to get there a little bit later in the stream uh good morning to you winterfell in fort lauderdale dipta is on their way to learning c sharp uh till now i know object-oriented programming concepts do i need any special prerequisites um you can go back and watch other videos in this series on youtube go to the.net channel click into the playlist learn c sharp with c sharp fritz and i'll walk you through the basics uh i believe in chat you can you can let dipton know what you think of of the series here i think we've been pretty good there might be some things we could have done a little bit better but i'm kind of proud of what we've accomplished essan good uh good afternoon to you in iran um let me i'm gonna skip through a couple folks here keith ornette hello to you in huntsville osman in the uk hello hello uh can i talk about parallel task async we are going to talk about parallel for each um spooky coders in austria austria not australia uh sodiq in qatar great to see you amal or shia hello hello no sorry the hat bot does not run here if you go over and watch my show over on twitch uh on tuesdays and thursdays i have a ai that sits in chat and will tell you what hat i'm running i'm doing well today diego's in brazil um i'm gonna skip through a couple of these task versus threat i'm not even gonna recommend or get into thread today we recommend everybody uses task now uh task await all versus parallel for each we're going to task when all and i'm going to show both of those locking on current objects not going to talk about that sorry talking strictly about tasks and and how to get that running those concerns around interacting with locks and concurrent objects a little bit further down we're not going to get to today um [Music] uh repository pattern is great using onion architecture fantastic rizwan is here from 2025. dude let me know what's going on in 2025 are we all on like hoverboards and and flying cars and stuff uh that's pretty cool good afternoon yen's good to see you um 99 of the time it works every time yes and we're going to talk about that as well uh the concepts from basics yep we're going to talk about that would i cover ie sync and um no sorry it's a little bit further down github or git lab i work for microsoft github um that said i have a gitlab server installed here in the home on my home server so nothing wrong with using both um but when it comes to building and deploying with enterprise trusted environments github um good afternoon to you nitro evil how's it going there underscore um how do you become a c-sharp mvp you need to be nominated to become an mvp um somebody who is either in the mvp program or a microsoft employee needs to nominate you check it out at mvp.microsoft.com it going there unesco good to see you um wayne hello good morning to you in california you're following that series dipped it fantastic is task a high level implementation of thread or something else something else well it's it's an abstraction over threading and asynchronous processing you're going to see more about that in a bit herbert good to see you in taiwan uh why.net does not have async events events by their very nature are asynchronous so you don't need to call async on it because they're being triggered from another thread somewhere else um uh yvonne hello to you in peru uh terry's for dialing in from the carolinas johnny b cat is here waiting for the github versus azure devops shakedown uh it's a good question jens is it is here from australia good evening to you whoo all right we've been through the entire list of of chat messages my goodness so much going on there thank you so much everybody that's tuning in let me get some music playing here in the background this is of course stream beats from harris heller i'm going to be playing the synthwave playlist today this is music that's designed to be royalty free dmca free you don't have to worry about anybody chasing you down um like the cobra kai the skeletons and the karate kids anything like that um all of this is available free no royalties needed you can uh stream on your favorite platform with it um and you can get access to playlists for amazon music apple music and spotify check it out at streambeats.com thank you so much to harris heller for making this music available for us today why is chat so chatty eggsy because this is a fun topic today talking about multi-threading and getting more out of your processor and and yeah all those cores that you've bought and you've installed can we find somewhere the past streams um yes check it out youtube.com.net there's a playlist there called c sharp with c sharp fritz you can click in there and you'll see more of these scripted videos my channel you can find on youtube.com c sharp fritz and i cover all kinds of different topics over there we've been bouncing around on a bunch of different things dimitri dimitri who asks is it safe to run async tasks in infinite loops yes uh considering the app does not get reset like an is yes it is you're going to want to be able to cancel those we're going to talk about cancellation tokens today there as well operating system is more than just threads i o completion ports file handles yes exactly mamut async await is a higher level concept that abstracts away all of that so that all that you as a net developer have to think about is just wait for this thing to get done it's gonna fire and we'll see what happens when it comes back samuel hello to you in brazil um hello is that kumbaka in indonesia hello hello uh you've been a software developer for decades but i still find async awaited challenge totally agree totally agree this is not a simple concept let's start with that let's start with the the concepts we're going to get into today are around asynchronous programming and multi-threading those are two different things and they're a little bit further off everything that we've been doing to this point has been synchronous programming that is code progresses from the first line that you pass in to the next to the next to the next synchronously in order okay when we think about asynchronous processing that means that things kind of bounce around and happen in different order and when we think about multi-threading and asynchronous processing we'll we'll see how you'll call out it'll go do some things and eventually it'll call back and continue and pick up where it left off multithreading is a way for you to send tasks for you to send different programming instructions to be executed on different threads so when you execute things synchronously they start on a thread right there's the the processor our computer wakes up and says i'm going to start executing these commands and it's executing things on the same thread right there's a dedicated line of processing that's reading through and it's all in the same memory space and consecutively executing that code multithreading is a way for us to say give me a couple of those and we're going to send some tasks over here to that thread and we're going to send some over there to that thread and i'm going to coordinate and when everything's done do something else but maybe i want to do some things while those are processing and that's multi-threading now asynchronous asynchronous code can behave multi-threaded like because you're going to call off and say go do that thing over there and while that's happening i'm gonna do some other code over here and we'll see some samples around that in just a little bit here is task inherently async await it is not we'll talk about what task is in just a minute okay um but a task is a is a wrapper around these concepts that that async and await deliver to us we'll talk about that in a little bit a reef has is having trouble explaining to their colleagues async await and multi-threading let's let's talk about that they believe async await is multi-threading and it is a common misconception async await can be multi-threaded it isn't by definition multi-threaded you're going to say let me explain that in a little bit with some concrete examples when we get over to the uh to the full set debugging async is a pain yes nitro evil it is debugging asynchronous code can be difficult because your call stack gets tossed up into the wind here hello to you alejandro and the dominican uh vitor in quebec good to see you wait key back make sure i say that right like the way the gpu works yes a little bit like how the gpu works how's it going the s4 p0 good to see you can we say that async is kind of line jumps in assembly level programming kind of not quite kind of it's close a bit on value task would be great i didn't want to get into value task um i didn't want to get into value task we can i'll i'll try to get into a little bit if i remember later but it's a little bit further a little along that's right it is vm level but making a comparison making a not saying it is assembly level there jin but it's um do to compare it not saying that it is but uh uh using a metaphor um hello to you fred in ghana it is a code gen trick that's right imminson it is uh uh yeah it's it's similar in concept not quite this it's it's not implemented the same it is a cogeneration trick that we're using so uh how's it going there aditha adithya uh jorge says chili chile is present too fantastic uh hey there what's uh what's up baby okay um so i i got a new piece of hardware over the weekend and i'm i'm kind of thrilled i bought it specifically for this show you may have seen me when i'm reading when i'm reading chat i'm always doing doing this looking at my confidence monitor so i got my hands on a uh on a teleprompter so that i can put i can put chat room right in front of my camera so when i get into when i get over to the other set which is right back there when i get back over there we'll um you'll see i'll be reading chat directly off of the camera so i believe this will be a better level of engagement because when i'm reading your messages i'll be looking right at you so i hope that isn't i hope that isn't creepy but i think it'll work um how to handle situations when i don't want to wait for code execution inside an async method is there a good way to create a fire and forget scenario yes i will show you that i've got great examples of that coming up here how safe is asynchronous link processing inside an async task inside a parallel 4-h it's not parallel for each and then async processing down the line like that it's not um i think async is like making a breakfast like a 200 series of learning c sharp in the dot net channel we're gonna look at the breakfast example and yeah yeah uh what's the difference between asynchronous programming and synchronous programming nikhil we're gonna see that in just a little bit as well that i've already got that loaded up here that's president level hardware cool hey look at that um what am i doing when my stack traces stop it move next i don't know good evening to you sir off in egypt all right we've said hello we've welcomed in we've answered a couple questions we've gone through a little bit of chit chat we're about a half hour in let's go get set up over on the code and let's start talking about um let's start talking about our our code what we're going to work through today and um getting a little bit further on the async awaits so if i've done this right i'm actually going to look proper when i get over to the other the other set alright ah there we go there we go i'd run over my headphone cable test test there we go i'm over on the other headphones um are paradigms used in synchronous programming the same as async programming kind of yes all right let me head over to the other set and let's uh get things all cued up here and have a little bit of fun with this so i'm gonna go get in the code heading over to the other set doing the thing walking over here i am oh no yeah yeah yeah there we go um fantastic and it worked just the way i wanted it to feel so good we're gonna talk about that in a little bit back over here and let me clear all the outputs right over there async await and multi-threading um let me see i should be able to control there we go uh can i show all multi-threading debugging tips no i'm not going to be able to get into that today what's the difference between async await and promise is there a promise equivalent in c sharp um kind of kind of it's it that's what a task is and we're gonna you'll see a little bit about that uh the difference is the same as ms-dos name is wind what um yeah uh ubuntu no no ubentober no well i mean we're continuing in it yes but uh we're we're gonna be over here much crisper sound i don't um so the other one is a dynamic mic where this is a compression mic so uh that other one shields out and doesn't pick up all the lows and highs and then it gets compressed again um is concurrency different from parallel no you're you're on the same line yes ubentober on the visual studio channel we're here we're live using linux i want to make sure that you're comfortable that you know and you're aware that linux mac uh windows they're all very welcome to be using.net to be using c-sharp it's it's a great way for you to be happy and be able to program your favorite programming language wherever you want to be all right um somebody was saying they really like visual basic yeah yeah um i like visual basic too but c sharp is really where it's at where you need to be um slow sunset vibes asks is a task the same thing as a thread no i'm going to talk about what a task is in just a minute all right so let's talk about what async await and multi-threading is i still haven't mounted the monitor over there so i can read everything while i'm coding here um so as part of the.net ecosystem of course we're programming with c sharp we've got full access to work on our machine and we want to be able to take advantage of all the resources on our machine that means connecting across the network accessing disk accessing other sensors and things that are on our machine that we may want to interact with and well on modern machines you've got a lot of cores on that processor you want to use more of that you want to be able to spread out that workload especially if you have computational intensive tasks spread that out so that it's not blocking what the rest of our user is doing right the our users are allowed to interact with the user interface and other things are going on in the background a great example of this if you're using microsoft outlook you can go into task manager and you can see exactly how many threads task mana uh outlook is using and it's always using a lot why because it's refreshing all the data for your email box and your calendars and all those things in the background while you're typing your emails scheduling a meeting doing all those things and we need to be able to juggle all of that so that you get a crisp experience and it feels like everything is running live when in fact there's other things going on in the background that are updating what's going on you see this also with browsers where the browsers are going and updating and painting different things on the screen as you're interacting with that so uh let's see missing on error resume next in c sharp why why would you want that no we talked about error handling actually last stream so now since c sharp 1 there's been ways for you to run code asynchronously or with multiple threads i'm not going to get into those techniques because quite frankly we don't recommend that you use them because you're going to potentially run into um errors scenarios that are going to trip you up um hello to you uh is that seal in south africa no worries about being late that's okay there's a rewind button on youtube so we recommend folks use these new keywords that have been made available for about the last 10 13 years called async and await now what async and await allow you to do is interact and check out i've i've actually written it right here it's like it's like i planned this or something so move the little hand thing fritz come on there we go so this benefits greatly for i o bound and cpu bound code so you've got a lot of code you're going through doing a lot of calculations um and and you need to wait for that to be done or you're going you're requesting something over the network you're interacting on disk you need to wait until that network request finishes a database request completes across the network and delivers you the results you're interacting on disk you can't continue processing until that interaction with disk reading a file writing a file has completed you want to make appropriate use of your resources so that when it comes back you're ready to pick up and continue working and you're not blocking other things from happening on your application so async code uses task of t type t and a task object as a return type it allows you to model the work being completed in the background so this is a little bit like a promise okay the task tells you is it completed has it been cancelled um and it gives you a handle that you can also wait for and say okay wait until that thing is done i can also say when it's done continue with and go do something else so the task is very important for us to be able to have that pointer to what's going on in the background the async keyword turns a method into an asynchronous method which allows you then to use the await keyword in its body so this is an asynchronous method do these things a wait for some other process to occur and continue processing after that so when the await keyword is used it suspends the calling method it stops it okay yields control back to the caller and says go ahead you can go do something else while the awaited method completes we'll see how that works in just a second so you end up with this go do something hey caller you can you can go and and continue doing whatever it was that you were doing i'm going to notify you when i'm ready to continue processing and pick up and continue the await keyword can only be used inside of an async method this is important you can only use it in an async method so um if you have synchronous methods we're gonna need to play some tricks to get it to continue working all right let me see what else is going on i see some folks in chat um i'm not talking about observable collections today sorry um perfect example of synchronous something using a single thread is the old command prompt yes that's a that's fine absolutely does this mean async awaiting.net has to use task return type um it doesn't have to use the task return type you should use the task return type so that you can you can process and handle it properly similar to how node.js works not quite but it's similar in concept does every async function return a task of t type it should so that you have some concept as to what the method is doing you don't have to um i'm using a loop to call a task that cannot be called again until it finishes what's the best way to do this uh yeah i would return a pointer to that task and and doing a a wait when all we'll see a weight went on a minute is it an anti-pattern to use async awaits when maintaining legacy code that was not initially async awaits i wouldn't call it an anti-pattern but uh i would say it's an unneeded um optimization that you don't necessarily need to do all right let's get into um let's let's get into this a little bit and talk about how and when we use these first off let's talk about why you would choose something that's cpu bound and i o bound and the different ways to handle that if your code will be weighting something from disk or across a network or some sensor there's another piece of hardware at play not the processor some other piece of hardware the gpu um a sensor or something that's running um a gps sensor right um those types of things are i o bound okay input up output you're waiting for something else to finish not this processor not um this application it's i o bound if your code inside your application is gonna be perform performing that expensive computation right if you're going to calculate pi to how many digits that cpu bound you're going to calculate prime numbers we've got a sample showing that today that's um that's cpu bound all right so let's start off talking about i o bound examples like getting data from the network all right i'm going to take a quick look at chat here um can c-sharp do multi-threading on the gpu using cuda yes i'm not going to get into using cuda today it's a different library that you can use to delegate tasks to be used on the gpu but you can absolutely do that all right so if we want to get data from across the network we clearly want to wait for that to return so i've got a little method here i'm using the http client this is native2.net i had to put a using statement up here so that i could get into the appropriate namespace where it's located so i'm going to use my new http client here and i wrote a little method get async and i'm going to go get some url so here right this is an async method returning a task of type string this is the typical syntax you will see for asynchronous methods this is going to run asynchronously and it's going to wait for us to go get that url clearly reaching across the network we're going to make that initial call we're going to wait for a server to respond we want to wait for all the data to be delivered on that request to our client and then return uh control to the calling process so go get all that data and when it's done getting the data right so a wait until it's done getting that data put it in this response object now the response object has a bunch of properties on it but particularly we're going to go grab the content of the response we can also grab things like headers and um and and the return type write the http code but we're gonna go get that content we're gonna say you know what read the content as a string but read it asynchronously once again where this is cpu bound here because the string is on our machine but it's going to be a really big string we want to load all that up and deliver it into whatever variable is calling this we're going to return that as that string right there so i can write a very simple method here that says await go get async.net get me the content of the dot.net website and when i run that you see it takes a few seconds and eventually it finishes and we see the html for the dot.net website and it stops there in the notebook and says okay there's more content i'm gonna just omit it here we can take that out and look at it later so i've gone i fetched data and i've returned it and it looks like for for the purposes of any other program that we've written it looked like it was a synchronous program even though things were yielded and other and and um right if things were awaited here it was handed off and other threads did that came back and our thread continued and quite frankly i don't care about those other threads go do your other thing over there return to me as quickly as possible all right now let me take a look back at chat and make sure that i'm caught up here um what's the best way uh to get the top end tasks of a array of tasks and stop awaiting others i'm too specific i'm not gonna answer that question drop me a line on the youtube uh youtube comments and and we can take a look at that later i'm sorry that's way too specific an example um the display has the await keyword though it's outside the async function correct um so what i'm doing here right i'm calling get async and i'm awaiting the response so think of this as a a single unit of method call right let me move that up just a smidge think of that as a single unit of a method call that's saying execute this and await it coming back this way right i'm i'm telling exactly how to handle the threading how to handle the response that comes back and i'm saying display it all right here when it gets done and returns what's up baby asks should i use net5.net 5 is our current release of net our current production version net 6 is going to be released in less than four weeks three weeks three weeks um so you should be able to get started with net five and i would then strongly consider moving to.net six um as soon as it comes out in uh november display is the caller that's right on line seven if we skip the await keyword what would happen spoiler alert that's where we're gonna go next can you have async properties no can you call async methods from properties no um you have to convert those to be synchronous if i want to call getasync method in the example should i add a weight if i would like if i would like to wait for the response yes absolutely let me show you that in a little bit i'm going to get into configure weight hold hold on to that we're going to get back to it how is it an async method when we immediately wait for the answer and run time wait for it it's async because it's happening on another thread it's yielding the thread in case there's um other things we want to do it the async and the await are an abstraction over asynchronous and multi-threaded processing if it happens fast enough it comes back immediately and there are no additional threads or things in use but if it takes longer it will yield the thread and allow you to do other processing so the response variable is not just a user created variable the response is not a user created variable here the response is the content the the response from the get method right it's telling me here's all the content and information about what um the http server responded uh what's the best approach to fire and forget i'll show you that in a little bit a lot of a lot of folks jumping ahead here um okay so let me scroll down to the next example i have here there's the explanation talking about this now asking well how do i fire and forget how do i do some of these other things so you can execute the method and not call it with the await in this case the net variable is not the response but is the task because we haven't awaited we haven't told the task let me know when this is done when you say await on a task the result that you get back is whatever that result is on the task so i'm then able to inspect the task and say well is this completed and i can interact with it i can say we'll wait for it to complete by calling the wait method there and i can display that result object by calling dot result and execute so i immediately get a response is it completed false it's out there executing i then called wait so i wait for it to complete and then i get the result so i haven't i i've i've fired and i've remembered the task that's important that i remember the task and i'm coming back and saying well wait a little bit in fact i can copy this display down to here is it completed immediately no it's not i waited till it's done yes it is completed and i'm displaying then the result here's what it is now to the question of fire and forget if i don't store that dot net task there your code that is running on that asynchronous method could be garbage collected and cleaned up so it's important to grab and maintain a pointer to it that's what the task is our task is a pointer that says here's the process that's going on here's all the information about it so that we can inspect and see what's happening we can figure out has it been cancelled has there been an exception thrown has what's the state of it is it completed wait for it to finish all these things that you may want to know about that process you just kicked off um i think it's all delete to hide it there we go all right let me take a look back at chat catch up with some other messages here uh what's the reason for having no asynchronous properties um properties should respond immediately you're inspecting something if you're going to get something that needs to run asynchronously that's a method um [Music] wait is something like a semaphore no no um what are the possible problems running an async method with entity framework um you shouldn't have any problems running async methods in um entity framework those async methods and entity framework should respond when you've got data available so they will implicitly return task of type t no you need to explicitly declare task of type t in your async functions like i did there task of type string move that there we go you need to explicitly declare you're returning that so that um your c-sharp methods that call this know how to respond how to interact with that um [Music] what's the point of weight well if you're firing a task and you want you want to wait for it to complete you call weight or you call a weight in front of that task and it returns immediately so line one starts the async process but line three let me go back to here line three says okay block and wait for it to be completely executed that's right yep bmos bat that's right um does multi-threading happen in processor or main memory well it happens on the processor you're going to allocate things in memory uh will this live video delete after i finish no it'll be it'll be persisted on these um learn c sharp with c sharp fritz playlist on youtube uh the weight prefix is pretty much just doing the dot natalie that's correct yep i've heard async await is not actually a different thread that's right it's not actually um but it is it it's an abstraction over it you're not necessarily on the same thread we'll talk about that is there a way to create a task and evoke it somewhere else yes so we've um right we're we have this task that we've been handed and it's actually already processing right you can create a new task and pass that around um that's a little bit further along than i want to get today continuing here in which scenarios we should not use async and await when you need to do something synchronous when is it advisable to use weight compared to a weight um you want to use dot weight when you need when you're passing the reference to that task around and you need to inspect that task otherwise use a weight um no it does not implicitly return type task var.net does not return type task there is no implicit with tasks you must explicitly declare that your returning tasks tasks are never implicitly used in c sharp um a print test to a network printer fire and forget yes but you need to keep track of that print task because if something happens to that printer paper jam um right the printer is offline you sent that command to the printer well what happens if there's an error you need to keep track of that so you can report back hey there was a problem there was a mistake we need to process that um why use a weight when you want to use the response from the asynchronous process well right yeah yes you only use a weight that's correct and you don't need to inspect and get into and do things a little bit out of process here what's the point using async await and server side code there is no ui in comparison to blocking calls just inefficiency of operating system threads no um think about it if you're building in a website the the website the web server only has so many threads so while you're waiting for data to come back from your database or from a microservice yield that thread so that another another request can be handled yield that thread go finish let the database or the microservice finish when it's done pick back up and send the response to the completed response to whoever called the web server so can you get inconsistent results mixing async and sync calls um that's a very that's i i don't know your scenario it's always possible to have inconsistent results um okay i'm gonna continue on here so we showed without the that we get the task back that we're then able to interact with now we can do things then we can fire multiple async operations like like you would if you had two tabs in your browser right let's go get on one tab let's go get bing.com on the other tab let's go get dot.net see what i've done here see this is me continuing the microsoft branding properly you see what i did there i i could make this minecraft.com but looks good all right so i'm going to say go get those two but notice i'm not awaiting them so that means when i look at the bing variable over here it's a task when i look at the dot net variable over here it's a task also i can then use this when all method to say a wait for all of those tasks to complete and then continue processing so a weight blocks at this point it says go finish what you're doing there release the thread go do something else i'll tell you when i'm done processor so that you can pick right up on the next line after this okay so wait for both of these to say they're finished and then continue processing and you can pass in any number of tasks they're not just a comma separated list you can pass in a collection of tasks there to say when all of these are done continue processing um so when they're all done then i'm gonna display here's the bing html length here's the net html length and i'll say the total elapsed milliseconds for those requests and it was one well it says right there 1.2 seconds but it was 12 28 228 milliseconds now if i did those consecutively if i had done a weight here like this right it's going to run the first fetch out to go get bing then it's going to run the fetch to go get it from the net website and here i'm not inspecting the result anymore i have the result because i awaited so if i run it that way now all right see now because of caching i look i look like i'm lying it's adding at 0.7 seconds let me turn that back i should have run it a second time uh when it was in the previous model should have run it a second time otherwise the demo looks kind of cheesy i knew that and i knew that because when i was testing this i was like wow that's really fast there we go so now when they run synchronously asynchronously i get it in less than four tenths of a second it doubles in speed because it's running both queries to both websites at the same time and it's only returning control to say continue here when it's done requesting both of them there's other methods that you can take a look at here to help with some of that concurrency management when any so i can say well when any of these are done continue processing okay so i'm gonna do when all there so that kind of works out let me take a look back here at chat and catch up here does async await uh work the same as javascript's async await with event loop i believe so um and right here you're seeing the cross pollination of programming languages where c sharp developed this feature as a shortcut for asynchronous processing way back in 2008 and just now but not just now but right it's making it its way into other programming languages um will there be a replay it's recorded and will be available on youtube later youtube.com.net how to handle concurrency not going to get into concurrency i'm sorry um it's a look that's a little bit further down um continuing weight versus get an awaited get result right that's exactly what you just saw there does the weight need to be in an async method no the weight needs to be on a um it needs to be run on a task though so uh does this when all block the main thread no it doesn't the await releases that thread and comes back i could do um i could do task when all dot wait move move yeah yeah yeah right and it comes back that way all right so i'm awaiting all of that i'm calling dot wait to say well just wait until it's done that blocks the thread calling weight blocks the thread calling await releases control so you still get some responsiveness and then comes back when it's done yes we're going to look at parallel for each in just a little bit so yeah caching caching bit me there didn't it if the async method waits for a response is the same behavior of an async method isn't it it feels like jeremy it feels like the same behav behavior as a sync method and to um to to developers it makes writing those asynchronous interactions so much simpler right it looks and feels like an asynchronous method like a synchronous method like your normal coding which is exactly what the language designers wanted you're getting better performance better use of your hardware without having to go and handle we'll start up a thread and run this asynchronously here's the callback method to call back to so it knows how to continue there's a lot of back and forth code that happens there that's all being hidden from you the language is getting is delivering that feature for you without you having to do all of that work c sharp got inspired by javascript kappa yeah yeah uh the other way around javascript features have now been significantly inspired by c sharp thanks in part to typescript is this the same as parallelism not yet what you're seeing here these aren't necessarily parallel tasks they're two asynchronous uh methods that are being called at the same time um so i guess in that sense they are parallel it's not explicitly parallel we'll see more parallel later [Music] does task wait block the calling threat yes it does answer that um hey 3d poly wraith hello hello all right um what's this async await best practices yeah there's a whole bunch of discussion out there and we're going to get into more um and i've got some links to that as well what if a task takes too long you can cancel tasks i'll show you that shortly as well so task object um right i mentioned and blah blah blah you can read this but we can also say continue with so when you execute continue with right so here i've got get async and right so goget.net and then continue with here's the next thing to do now right this is going to run asynchronously in the background but because i'm not awaiting it i'm getting a task coming back right if i mouse over this there it is it's a task that's being returned but i've chained on to that task and said do this thing next i'm going to display task is completed and here's the length of the html that i fetched from the dot.net website i'm then going to display checking.net complete state and then await the net task so we're going to first set up this task to go and get the dot.net website i've got a slash in there and i've told it here's what i want you to do after it and i'm going to await that entire block it's going to go get the data it's going to continue with and return when it's done so when i run this now you see it immediately comes back and says not complete right because i have that task and it's still out of asynchronously running i'm going to await it to complete and when it completed it wrote out true and there's the length of the.net website let me show you again immediately comes back false right instantaneous processing because that's the next line we're not awaiting we're not blocking we're not releasing the thread immediately come back and that other process that's happening that we're waiting for eventually comes back and we get true in the html length so we're now chaining things on and continuing and specifying other things to happen as our processes um happen uh complete i'm sorry can you use async oh wait dave asked continues async a way to spawn off a method to create a pdf for example and then let me know if it completed the task we're going to see in just a little bit we're going to ins that's a more cpu intensive thing not i o intensive and we'll use a structure like task dot run that we can await that task go create the pdf let me know when it's done and we will await that task that's running so we're notified when it's done and we can continue processing um if it's not parallel do you still need locking for thread safety you do you don't need you don't always need locking for thread safety um you need it depends on what you're doing um but you're you're going to want to be careful so that things stay thread safe pass instances of things so you're dealing with instance variables of things it's when you're dealing with statics that you're going to run into issues of thread safety um yeah have i shown how async and weight implements the feature no i am not getting into implementation that is way too complicated for what we're talking about can we use serialization serialization tony um absolutely does some asynchronous processing because it's cpu intensive so we want to release we want to release uh control of that thread while we're working through here um how to decide when is efficient enough to use async methods in your new defined classes depends um if you're doing something that's i o bound or cpu bound that's when you're going to want to make that decision if you're not don't need to do it um do i recommend using async methods as much as possible only a sith speaks in absolutes isn't that isn't that what they said in that movie um i'm not going to recommend that you use them as much as possible i'm going to recommend when it's appropriate when you're interacting with another device when you're interacting across the network something that is i o bound i would recommend using an async method you don't have to but i would recommend it uh we're going to talk about configure weight false and i'm going to say no it is not a good practice um what happens if i do two awaits after each other um they end up just like we saw up here they end up running right so i ran it here they end up running synchronously right so there it's cache now and if i run two awaits right after each other right it ends up running them synchronously so it takes longer because it runs the one waits runs the other so that may be what you want but if you want to get more out of this get a little bit more speed out of it there we go you're going to want to run them in parallel right so that one kicks off and runs then the other one kicks off and runs and you wait for them both to complete and come back can i explain a use case i'm going to get into configurate configure weight is is very much misunderstood and if folks think that it is the answer to creating more speed in your system and you can actually create a little bit of chaos going in there uh get a waiter get result in one thread applications yes i'm gonna show you that in just a little bit tell us about deadlocks um i don't want to get into deadlocks too much is it bad to use async at a weight in dot-net core environment no not at all it we think it's terrific to avoid thread starvation yeah it handles that for you is this similar to how concur i don't know go lang i'm sorry um can async processes utilize the benefit of multiple cores yes absolutely that's why you would want to do that why is configure wait the questions about configure weight are strong i promise you we're going to get to it it is it is an advanced topic that the people who ask about it quite frankly you've been misled to think that it is a performance thing that you must do everywhere it is not we'll get to that in just a little bit i promise you um we can force async methods to run synchronously so we want to we're inside of a synchronous method and we need to block you can add on to the end get a waiter get result let's wrap that so it's a little bit easier to see here okay when you do that it says get the awaiter get the thing that pointer that's holding on to what's awaiting over there and get the result when it's done and that will hand off and allow things to process the weight is the other method that you can use to make sure that things come back and i'm blocking and waiting for them there is no asynchronous processing happening there okay i wanted to show the breakfast example next this is an example from the.net docs around how you how asynchronous processing is important and how it helps with how you build and interact with your code um so if we were making breakfast um i've got juice toast bacon eggs and coffee and we've got some methods for how we prepare breakfast we're gonna pour orange juice we're gonna write out that we're pouring orange juice we're gonna apply jam to some toast putting jam on the toast apply butter putting butter on the toast we're gonna toast bread and we're gonna pass in some number of slices and we're gonna put slices of bread in the toaster and we have to wait three seconds while it's toasting right and then remove the toast from the toaster um and of course return our toast we're gonna fry bacon put a certain number of slices of bacon on the frying pan we're gonna wait for a certain number of seconds for the bacon to cook and then we're gonna flip it cook the second side wait a little bit and then put bacon on a plate and we're gonna do the same thing with eggs warm up the eggplant wait for it to warm up crack eggs cook eggs wait for it to put the eggs on a plate and pouring coffee just happens immediately and these are all synchronous methods it's way too slow if that's how you make your breakfast if you first pour your coffee then go fry eggs then fry the bacon then toast the bread and when the bread's done toasting apply the butter and jam and then pour the orange juice if you do it that way you're pouring coffee the coffee's ready waiting for the eggplant cracking the eggs cooking the eggs eggs are done okay putting the three slices of bacon in the pan and my eggs are getting cold flipping a slice of bacon cooking the second side bacon's ready bread's in the toaster toasting remove toast finally pour the orange juice and breakfast is ready but down here at this point my toast my bacon my eggs are all cold so you want to do things a little bit more asynchronously so if instead we toast bread asynchronously and we await while those three seconds are going on that that the bread is in the toaster while that's happening yield the thread and go do something else right i put the bread in the toaster push it down so the toast starts toasting i can go start cooking my eggs instead of staring at the toaster and waiting for it to finish okay same thing over here with cooking uh cooking the bacon i'm going to await task delay i'm waiting those three seconds well yield the thread while it's there cooking i can turn away and take the toast out of the toaster when it's done other things like that same thing with the eggs i'm going to a weight task delay now of course in real code right it's not a weight test delay maybe it's writing a file to disk or calling a microservice or something interacting interacting and calling an iot device that has a servo like in doc brown's lab that's actually flipping the eggs or something right there's the back to the future reference for you right it's doing something behind behind the scenes with some other piece of hardware we're waiting for that thing to happen for the purposes of this demo just to make it a little bit clearer and simpler i'm just awaiting for those so now i can say let's start off by pouring a cup of coffee start frying our eggs start frying our bacon start toasting the bread and await the toast wait for the toast to be done because when it's done i'm going to apply butter apply jam and then the toast is ready pour the orange juice and now that i have my toast my orange juice and my coffee well let's wait for the eggs to be done and say eggs are ready wait for the bacon to be done and say bacon is ready and then breakfast is ready so now when i run this look at this look at how much faster it's happening right done right uh yeah breakfast is ready all done so poured the coffee warmed the eggplant put the bacon in the pan the first side of bacon was done while the first side of bacon was done it started toasting when it was done as it was toasting we flipped the bacon cracked the eggs while the second side of the bacon was cooking cooked the eggs removed the toast while the eggs were still cooking buttered and jammed the toast the toast was ready poured the orange juice then we put the eggs on the plate we put the bacon on the plate because the bacon is ready so that's more like how we make breakfast you're multi-tasking multiple um things are going on whether it's the pan on the stove it's the toaster we're waiting for these things to finish in order before i get to the discussion of configural weight let me catch up on chat we're going to talk about configurable weight next and and i'm i'm going to be brief and we're going to get through this that's right uh howard it is a edge case and we're going to talk about that it does create interesting behavior yes um asp.net mvc crud app and azure app service with azure sql database should database calls be asynchronous yes um yes is when all needed at all yes just start the task without async then one by one get the results you don't know if they're gonna get done at the same time or not in the case of of bingan.net they're gonna return pretty quickly and they should return in order like that but what if i go out to some website that might be taking a long time what if i go out to ticketmaster.com right i'm going to order tickets or stubhub and i'm going and i'm saying go search for tickets to uh um write to the to the uh whatever concert right i'm trying to not show my age here um right i'm getting tickets to the taylor swift concert that's for you christina warren i'm looking for those tickets i'm doing a search well searching for tickets for my favorite venue is going to take a little bit of time where getting the content from bing.com is going to return immediately right the search engine home page is designed to come back in less than a half a second where searching for tickets in in my favorite seating area at at my venue at the at uh lincoln financial field the football stadium here in philadelphia it's gonna take a little bit it might take 10 15 seconds to search for and give me a list of tickets that i might be interested in so it's not always going to run and come back at the same time certainly dev you have a super air fryer says 3d poly wraith nice can we wait for an event to happen rather than a fixed time well that's what task uh when all says is task delay the same as thread sleep asks them all yes it is task delay is is it behaves the same but behind the scenes it's different thread sleep says block the current thread for this amount of time test delay says come back to this threat yield the thread come back after this amount of time um it's asynchronous as well where thread sleep pauses it blocks the current thread for a certain amount of time um yep thank you for the links into the dotnet docs do we have a link for this notebook you can um get the notebook [Music] you can go out to github.com c sharp fritz c sharp with c-sharp fritz and it's inside the notebooks notebooks folder and it's not on this branch just yet it's on oh shoot it shouldn't be zero two zero nine but there it is async await and multi-threading down there is where you're going to be able to find it right there so that'll be merged into the main branch when we finish um today's session let me see what else do we have here catching up with chat getting tickets to crosby stills nash and young see even calling it csny that that's a lot so uh all right let's talk about configural weight and this is something that i think folks have jumped into and said and and they've been told that all they heard was this is faster so use this everywhere and that's not the case it in 99 of the scenarios when you're building an application you do not care about you should not want to do anything with configure await i have a link down here in the in the notebook to this article from steven taub called the configure await faq any steven taub is is the partner engineer leader of the task parallel library the async await features um he knows the performance of net inside and out and and we're going to summarize what he talks about here you can read this article to go in depth it's linked in the notebook so that you can you can jump through and read this if you want to know the nitty gritty about how all this works but it gets into things like synchronization context that i for this session are a little bit advanced for beginners for you as a beginner that's building an application whether it's a windows forms application wpf a console application a xamarin application that's running on ios or android an asp.net website a blazer application you shouldn't consider this it's an advanced thing that nine times out of ten is not going to get you better performance so folks have been kind of tricked into this you don't need to do this unless you know you need to do this okay you're going to trick up your threads and it's going to be a little bit ugly all right can i drop that link into chat um uh over can somebody can somebody grab that link from the notebook and and drop it in there devbloxmicrosoft.com.net slash configure await dash faq and you can read that okay what configure weight does i've gone through and i've given i've given the disclaimer about about it but what it does i mentioned async await comes back it yields the thread and it comes back when it's done and says okay i'm going to continue processing configure weight is has a boolean parameter that it takes in that indicates whether it is required to resume on the current thread or if it can continue on a different thread if you're building some large multi-threaded thing that might be desirable to allow it to continue on another thread when you're building that gui application like windows forms or wpf that handles a control action a button click or something like that and you need to update the user interface because after you click the button it it committed an order right it charged a credit card something like that that happened asynchronously you need to update the user interface on the same thread configure a weight is configured by default to come back to that same thread so that in your application you're back on the same thread when the process is completed and you can update the user interface appropriately in web applications you're going to want to return to the same thread in order to respond properly to the client think about it the web server has many threads let's say it has 10 threads just for the sake of discussing and you're coming through on the first thread and you're making a request to the database you're going to yield that thread for a little bit while you're waiting for the database to come back if it came back and it and it didn't return to thread one but instead returned to thread five you're sending the response data to to somebody else that's wrong that's bad that's really bad so you don't want to do configure a weight false and allow things to come back on different threads when you're running in that application model when you're building a framework when you're building something that's that's a shared library that's going to be shared to other locations to other applications and you are taking control of the threading and you are managing exactly where things pick up and continue processing and that's an advanced topic that not many people do then you may want to do configurate and the net team has used configure await appropriately throughout the base class library throughout the runtime so that you get the best performance for how you interact with your code let me continue scrolling through chat here a little bit thank you uh chris jones and what's up baby for sharing some links there appreciate that over on twitch um most of the time configure weight is not needed that's correct you're you're going to be over over optimizing on it and where you think you might be getting better processing because you're just grabbing the next thread to work with you might not be returning properly to what's called so you do have access to old school stuff like mutexes are very much around semaphores absolutely and you may want to use those um when you're working with multi-threaded code so let me show you um i'm going to i have a method here make eggs and i'm going to display the current threads manage thread id i'm going to delay two seconds but i'm going to configure await true through two seconds later i'm done making eggs now show me the manage thread id and when i run that it's on thread four and then it's on thread 87. now for the purposes of the notebook that i'm working in that is okay that's fine it's updating and painting things and returning appropriately right but when you're in these other situations where you're inside of an event handler or you're inside of a managed thread around you you don't want to return on different threads you're going to run into issues is the thread a cpu or logical thread see that's one of the benefits that async await gives you you don't know and you don't really care because it's being handled uh by the framework for you um visual studio studio gives a warning when you use configure weight is not included it's been a while since you tested this it it you shouldn't be getting that when you're working in net core or net 5.96 great video from brandon manic about using async await yep yep when you're writing an online game so there's sebastian there's a great point now you're doing something that is massively managing many many threads when you're managing an online game you're building a server now you've taken control of the threading right you're not just working inside of a framework like like winforms wpf or asp.net or maybe blazer you have control of the the threading at that point because you want to optimize for that and you know and it can handle appropriately when data comes back when it comes back on different threads that's a time that yes you may want to do configurate false but for typical websites web services don't do it you're going to create more problems than the performance you think you're going to to help with all right so we talked about these are pretty much i o specific things if you have to and i should i should rename this this should be uh cpu intensive tasks and tesco that's better so we've got some processor intensive things that we need to do we can call task.run to throw it onto a task that's happening somewhere else and wait for it to come back so it's similar to taskfactory start new method but does not return a task object instead it returns a task object that represent the work that was queued so you're queuing this up to be run on a thread pool somewhere else outside of the current thread so check this out i can have this method show thread info and i'm going to console.writeline the current thread id some string and the current thread id so i'm going to start off with show thread info and just application there it is um and then let's task run show thread info task and we'll wait for that task that was run to be completed now when i execute this this is what i mean when i say it might be multi-threaded it's going to optimize it saw that i can get that done really quickly i don't need another thread so it reused and handed it off right now if i put a um if i put a where was it i did i put a uh a weight in here somewhere right if i do task delay and let's just delay 500 milliseconds uh and wait for that okay run that again and now you see it comes back because it was a longer thread right because it detected this is going to take a little bit longer it went and put it on a different thread okay now they complete on the same time you make me sad this is gonna nope so that thread scheduling you actually you don't control when you test run it's just gonna go and do its thing and eventually come back right now it may happen on the same thread it might not that's part of the beauty of this is i don't care get done everything and bring it back to me appropriately um the true false of configure wait stop having meaning in net core um in asp.net core it does not have meaning there is no synchronization context um so it's not a it's not a um it's not something that'll actually do anything it's it's quite frankly ignored dib is a net interactive notebook so this is very similar to a uh to the python notebooks the jupyter notebooks we were using um but it's a little bit more um specific and has some net specific features in it now somebody was asking about long running methods well gosh what happens if there's long running methods um how do we handle that and we're going to use something called a cancellation token in the past what i've done to get around to deal with long-running methods is i've created a boolean flag somewhere set to false and i say while this is not false or while it's true go do these things and come back we're going to use a cancellation token that's a little bit better structured for that a little bit more thread safe that we can cancel and it'll interact appropriately with our task and we can listen for that cancel state and behave appropriately i see a couple more comments coming through on chat let me catch up over here um so i'm saying not to use task in the implementation of promises in the implementation of promises one punch mac i'm not sure i follow um what about mono and net six will that still have synchronization context i don't know i'm not familiar with how mono is is implemented i'm sorry not going to be able to answer that um all right so cancellation token let's go back to that task run so let's do something here that's a little bit unsafe i've got a couple using statements so i can get my cancellation token source you see it right up there okay so the cancellation token source is a it's a source object that generates the token and communicates to everybody that's listening to the token the current state of it okay so i'm going to task run and while the token is not in a canceled state okay so while the token is is marked as continue running um and i i grabbed the token right here on line five i'm going to say wait wait one second when it is cancelled and it exits this while loop we're going to display test completed and i marked it with inner so you know that this is the statement coming from inside this now the task run i passed in the token as a second argument this is so that the um the task knows i'm listening to this thing for cancellation if it's been cancelled before the task has been started it won't actually start um which sounds kind of weird because you can write this can be created as a task and it may not actually be started yet so i'm then going to a task delay for five seconds and then say cancel call the token and say stop running and then i'm going to display task is canceled now keen eyes will see the problem with what's happening here when task cancel is called here it's a it it fires it flips the state of it and it may not necessarily complete if we're still waiting this one second if we're waiting this one second while it's been canceled it's not going to receive that signal immediately and it's not going to immediately stop so if the task is still running i need to stop it i need to tell it stop um so i tried doing the task.wait no it gets away and it actually ran out of control on this machine so what i've done is i've put a source disposed down here that says stop right i should be able to do like right um where'd it go uh t dot wait to ensure that it's done and now when i run it you'll see i start getting some stars and i waited my five seconds task is not canceled task is completed task is now complete that's here because i've inspected the task and i know it finished running so i'm running this long running process and let me shorten this now that you've seen it runs for a little bit let me shorten this okay so it outputs all my stars task is completed all right now if i didn't do that weight there it could actually exit out of this and still be running i need to stop it because i haven't but i've been processing continuing while it hasn't come back and finished it hit the the while here all right does that make sense let me catch up on chat here before i move some of this around and you see what's going on um yes the the the notebook i shared the link to the c sharp with c sharp fritz and you'll see the the notebook is right now it's in its own branch over here zero two zero nine that you're gonna be able to reach into and it's right there um the table i'll just merge it right now so it's right on the root and then i'll update it um why didn't it give me a new pull request from there do it create it and merge it there you go all right so now you'll find it right on the root in notebooks zero two zero nine so you can get it all right let's see can't you just pass the cancellation token in task delay so if i pass pass the cancellation token here right um you know what that might have that triggers a cancel on the inside so check this out that cancels this which then ripples up and cancels this task so now i get the indication that it was cancelled it it's complete but it was canceled it may have been completed correctly so you're right you're right and that's a another good way to solve that let me take this down so it's nice and short right so you can pass that token into all of the tests and i forgot about putting that in there and describing it so that it does trigger the cancel and stop the task immediately without that being passed in there i'm really just waiting on the cancellation right there but while you're triggering and running other external things you can always pass a cancellation token so while you're getting data from a database or making that http client request you can pass your cancellation token like this and if for some reason it was canceled application was stopped um some error somewhere else fired and you're in a bad state you can signal that token cancel and everything will stop processing good point thank you so much yeah yep normally cancellation token is passed as a parameter closed browser that's another good example burger b yep yep if it is a long running process it is a good process a good uh practice to pass the tokens you're right over on twitch howard i'm sorry on youtube howard mentions that yes um i'm gonna get done a little bit early this time so what if i want to explicitly run a series of tasks in parallel for a collection we normally have a for loop for that well we have a parallel object that we can execute a for each method on it and say for each one of these things run it in parallel so we can say parallel dot for each specify the collection and then the method to call it's not a typical for loop statement it's a little bit different because you're running this concurrently for each loop let me show you so uh we have this sample it's the prime number example from the microsoft docs i've copied it in here and there's a method here is prime that has the formula to determine if we have a prime number okay um scrolling down we're going to get prime numbers synchronously by just saying get the prime list for the passed in list of numbers let me just let's do that make it easier to read and we're just going to say take the numbers where it is prime cast it to list done there it is it's going to just do a loop across those and return the list of prime numbers i can also run that in parallel i just wrote a little variable here prime numbers is a concurrent bag we're going to get this is a concurrent collection that we're going to be able to insert into of the prime numbers that we're going to discover i put a little display here to show well here's the number of processors on this machine my number will be different probably will be different from your number when i run this okay and i'm going to create some parallel options here and i'm going to say max degrees of parallelism how many parallel threads are we going to allow to run this well i'm going to say the processor count let's wrap that again i need to think of wrapping this when i create these things make it easier to see when when i got this guy standing over here next to it so run just the number of processors that we have and here's the parallel for each for each of the numbers that are passed in use the parallel options max degrees of parallelism the number of processor the number of processors in this case and we're going to take each one of the numbers in that collection as we go across the loop so here's the input and the method we're going to call if it is prime insert it into the prime numbers collection done return that collection of prime numbers so i'm going to say give me 2 million up to 2 million enumerable.range give me the numbers from 0 to 2 million as a list start a stopwatch and go get the prime numbers using the synchronous method okay then we're going to do the same thing create a stopwatch we're going to run in parallel stop the stopwatch and display a little report here classic for each loop parallel for each loop and when we run this on this machine i have 16 processors 16 cores okay on the regular for each loop we found 148 000 prime numbers and it took eight tenths 800 milliseconds doing it in parallel with my 16 processors took 110 milliseconds an 8x speed up because i did it in parallel now i specifically put that option here max degrees of parallelism to show you well if i make it let's just say two just go to two run it again you see it speeds up roughly by 50 roughly and there's um of course diminishing returns on that as we ramp up that number if we go to four and a little bit less than four x faster and so on and so forth right if we take that to eight right not quite a little bit less and of course if i let it go with the entire number of processors so we didn't get too much more out of it when we went to the 9th 10th and 11th 11th processor but using that environment processor count is an appropriate limit to how many you want to pass through sure i could say run it on 100 it doesn't add anything more because now you're scheduling threads on processors you're backing up okay you're not going to end up getting any more parallel capabilities so realistically the maximum number of parallel threads you want is the number of uh processors on your machine let me take a look back here at chat catch up here can we create a ui to manage running processes and cancellations that's what task manager is but yes sure absolutely you can you can put all of those tasks into a collection and inspect and report the state of those absolutely um is that var limit two million result in int yes so uh mega mr marlborough asking about that two million syntax that i used here so this is actually um making use of i think it's a c 7 feature where you can use underscores right there to delimit the size of your number they're ignored by the process by by the c sharp compiler putting the underscores in there is something to help our human eyes be able to read the number and be able to identify oh 2 million you may structure that differently you may use whatever annotation you want within however many digits you want when you're declaring a number uh same thing goes with binary right i may want to put it every four characters in a binary number so that i have those grouped together as two bytes in a binary number okay so um continuing on here can i give a real case case scenario in web development where parallelism could be applied sure great example great example um i'm building a website that that shows a dashboard of data and i want to get all the data for the dashboard at the same time and deliver one package of data when that service is is complete so i'm going to asynchronously request from all those different places that i need data from my dashboard task when all wait for all that to complete and then transmit i could be doing a parallel for each if there was a collection of data that i want to inspect all of and return all of that as one block now there was a question earlier about using async await in the middle in the middle in the middle of the parallel for each there is starting with c-sharp nine the ability to do for each async you can do it it's a little bit dangerous and a little dubious to have async methods that are running on a background thread that are returning to a thread and and it get you it can get confusing quick so [Music] fair warning doing async in the middle async calls in the middle of a parallel parallel for each can get tricky and you can confuse things in in our human minds of how it should process oh loving that coffee today i've got about a little bit less than 10 minutes to go here taking a look at chat uh web apps that process an image that's another great example yep yep um can't get done early on async i know john right so much going on here um and i finally found the deck of cards that i meant to show we were talking about collections i instead i was using magic cards i meant to find i had this deck of regular playing cards i meant to use uh look at that these are from how far back in the day james way oh my gosh oh my gosh how yellow it is oh my goodness so um all right i believe that's all i had for today's notebook uh let me take a look at chat see if there's anything else that we want to catch up on threading allows you to shoot all six of your feet in one operation yeah can parallelism be used with entity framework to process data such as retrieving from a csv before finally saving to the database saving to the database using an entity framework context you see this with other interactions with the database if you try to update the database in parallel like that um entity framework will block you from trying to do multiple save asyncs with the same context with the same instance of a database context we haven't talked about entity framework yet so i'm getting a little bit ahead of myself an entity framework context is a way that you make a connection to the database so let's think about that as the connection to the database if you make sam several save calls at the same time to the same collection through the same table through that same database context that database connection and i'm i'm simplifying it's not necessarily a connection but for the purposes of discussion let's think of it as a connection you can confuse entity framework and it'll block you from making multiple concurrent save requests in the save being an update and insert or delete it'll block you from doing that at the same time it because it needs to maintain state so you need to cue those up and process them in the right order uh let's see here you got a threat safety error when passing a db context in parallel threat for each yep there you go that's right dave returning spatial results with yield uh what can we use parallel for each to work with downloads for example yes you could do parallel for each to to go out and and uh i'm trying to suggest something that's that's not that that's not illegal and i'm i'm i keep coming back to the scripts that he wrote at the beginning of the social network if you've seen the social network you know what i'm talking about but parallel for each could do that yes um running parallel for each to hit a bunch of uh uh [Music] or to to to update to notify a bunch of microservices hey this event happened parallel for each across the the microservice destinations that are scattered across a half dozen data centers go notify all of them at the same time that's a great example of doing something like that instead of the social network movie um you watch cause i talk with my hands all right i don't know uh yeah websites no not website scraping it's possible but i don't want to encourage that uh why do you we use double locking while implementing real-life use cases um double locking is used to ensure that uh that when you come in and make that second when you're the second request to hit the lock that it the process you're looking to complete wasn't already completed um hacking in movies is so terrible says drake over on twitch totally agree with you all right we are just about out of time i'm gonna head over to um to the main desk and let's call this a stream let's call this a stream i got done a little bit early but i think we answered some good questions headed back over oh man feels good to be back uh hey net jam jr thank thank you uh does task.wait block the calling threat oh that was from way earlier wasn't it yeah all right um i i think we got it i think we covered everything we wanted to today on this it's a lot to cover and that was really for for beginners right i want to make sure that that that's clear this was there are many many different facets to multi-threading async and await and for for folks that are beginning that are just dipping their toe into it i don't want you to be confused i don't want you to be overwhelmed i want you to understand and appreciate that this is a very powerful tool that you can use to make your applications faster other things right there are people that that like getting into the premature optimizations don't do it don't do it unless you really you explicitly know exactly how and why you're managing those threads because it's it's possible to to get into a dangerous situation um for some reason i lost my youtube there it is there we go uh thank you so much friends i appreciate the kind words over here as always i'm right here on mondays um 9 a.m eastern what is that 1300 utc answering questions talking about cool c sharp features and you're going to find me tomorrow tuesdays thursdays and sundays over on the c sharp fritz channel on twitch talking about talking about blazer and azure and all kinds of cool stuff yeah i'll see you tomorrow morning 3d polyurethane thank you so much really appreciate it so much knowledge leaking out of my mouth you make it sound like i'm drooling there man um oh my goodness all right let's um those of you that are watching on learn tv thank you so much for watching hope you enjoy the next program coming up if you're watching on youtube thank you so much for tuning in descriptions links to the notebook just below me here so that you can find more you can get all the samples interact with them tell your friends tell your families tell your pets tell your co-workers check it out so much that you can do with this and it's all in a notebook it runs right there in visual studio code whether you're on windows mac linux or you even want to run it in the browser right there on github give it a shot um i covered that carlos so sorry you can go back to that the notebook link once again what is if you are and you're not um do i still have it here no no let me grab it one more time and you're going to look for in the notebooks in the notebooks folder you'll find um all you'll find the async await multi-threading notebook in there0209 is what it's labeled um thank you so much everybody that's watching on youtube i hope you have a fantastic day enjoy the rest of the content on youtube there's we have a ton of dot net videos for you there's gonna be even more coming with dot net conf in just a few weeks i hope you tune in you stick around for that but for those of you on twitch it's time for a raid uh sorry i will not be touching teaching wcf uh we recommend folks move off of that um all right let's take a look at who else is streaming on the big twitch tv network figure out who we can get you connected with who we can send you over to magic cards that was that was previous time we did a little bit of that yep um i'm going to get you connected with who's this i'm going to get you connected with you know what we're gonna we're gonna check out one lion they are moving a vb.net windows forms application to blazer let's get over let's get connected to them send a raid over encourage and hope you have a fantastic time hope you come back a little bit later on the visual studio channel right here on twitch you're going to find the docs team.net docs team talking about some of the latest updates some of the cool things that are coming that you can find samples and and learnings out there and a little bit later mads mads not turkish mads christiansen will be back and he'll be hosting visual studio office hours that's all for me my name is jeff fritz i'll see you tomorrow on the c sharp fritz channel hope you have a fantastic day don't forget to sign up for dotnetconf dotnetconf.net i'll see you
Info
Channel: dotNET
Views: 8,608
Rating: undefined out of 5
Keywords:
Id: syCxCzhqA0Y
Channel Id: undefined
Length: 122min 36sec (7356 seconds)
Published: Mon Oct 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.