Async and Await, All the Things Your Mother Never Told You – James Clancey

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right good afternoon everybody how y'all doing all right we made it through the week almost you know so to put a nice end cap on everything that we've put together this week and learned we have James Clancy here and he's gonna send to you about a sink and a weight so taking away James hello everyone this is exciting so yeah so who is who came to the first evolve just curious show of hands Wow you'll notice from the first evolve to this evolve I've done nothing it's been awesome so I'm either doing something really right or really wrong so this is my only talk this evolved and hopefully it's on something fun for everyone it's going to be on a sink in a way if you were at some of my talks at previous evolves or things like that I hate slides I just do we're developers we like code so this whole thing is going to be code we're going to use two files mainly one brand-new solution there's nothing in it aside from an app delegate that sets our new view controller I'm using iOS but this is not an iOS Talk it's for iOS and Android but iOS simulators way better we all know that so nothing here is platform specific at all I'm just using iOS for ease of coding so I have a new empty class our view controller and as I said since it's an iOS one we need to do UI view controller I was hoping to get some of this type before the talk started but as you can see I did awesome at that all right who was in training who did the async and weight stuff in training okay good portion of you battle of 25% it looks like from up here I also like to do things a little interactive can be hard especially with me up here and big room but we're going to show of hand stuff and things and to do this though we're going to write some very basic code that everyone in a mobile world is pretty much written at some point or another and we're going to evaluate it and see what we're doing and how it works and we're going to play a little game though so to start our game I do need to write a function void what thread am i we are going to use this method throughout this talk especially towards the begin we're going to figure out what thread we are because async an weight is great thing there's a lot of common mistakes I start seeing with a sink and weight when people start start using it it's really it looks so magical and you're like what is going on this stuff just works and you just stick this async and await keywords everywhere and everything starts doing things so what I'm going to do is hopefully why is it not adding just using what I know I'm on this alpha Channel from a week ago not even the latest bits I should have updated before the talk but once again to having too much fun or evolve alright so we have our UI thread we're gonna do a little function here to figure out what's right we're like I said I want to use this all this async and await keywords and just magically it starts doing things very synchronously but until you start understanding what it's doing and why and really what thread you are it's really hard to figure out what's going on and to figure out your bugs with asynchronous code even with throwing these magical functions in there a lot can go wrong now I'm going to say that our UI thread is equal to thread dot current and I can get away with saying this because we all know our app delegate the finish launching fires on the main thread and it happens when this thing is constructed so I can just say our UI thread is the current thread now I'm going to be saying this is that where I'm always gonna be burning this to the main thread of the UI thread and if you get a technicalities that's not always true but for the for the purpose of this you should always assume when you're being called you're being called from the main thread especially with mobile apps if you lock a thread it you should assume it's the main thread because you're locking the UI there's a great potential of that almost everything comes from the UI thread anyway so we'll do one other thing we'll do Buhl is main thread use our nice little 6 C sharp sync tax UI through UI thread equals thread current all right so now we have a little thing we can call is main thread all right so now we'll just do make this thing nice and pretty we'll do those console dot write lines we all love so much and then who doesn't want a bunch of legible quotes there I've seen all of you doing this in your logs you can find the one you want it's fun especially when you start seeing everyone doing this and they all have their own indentations of it so they can start copying it and making sure it's visible mm-hmm you guys know what I'm talking about all right delete this one almost there and I have some eights in there why not console dot write line actually I'm gonna throw a couple other little helper methods in here because not only do we want to know if we're the main threading up we all know where this came from because that will help us we're debugging this later so we'll do call our member attribute and we'll just say what is it method a whoa whoa whoa I need to type string first method and if I make a mistake which I do a lot on stage feel free someone yell it out I don't care it's really helpful and we'll even say call our line number as well so you can say line and line equals zero all right everyone's use those before their compiler tricks they will tell the compiler to automatically pass that thing in for you so that way when we console about right line it'll tell us what method and what line number awesome for your logging libraries also once we're done I'll post this code so everyone can have it so now we can do console dot write line and once again I love my C sharp stick syntax hopefully you all do too but we'll say method and we'll even say line number what did I do oh wow yes line all right line and then we will also say one more thing and this is the big one is main thread all right let's put some of this jazz down here cuz why not and yes and I should make these different because sometimes they collapse tough all right so now we have a nice big method that should be yelling at us in our log saying are we on the main thread or not and for sanity check let's check this will say what thread am i all right put a breakpoint here I do not know how to zoom this in if anyone does I can do manual zoom so we'll do that hide the wall chides and threads we don't need any of this stuff alright hope I know what I'm doing yeah that doesn't make it that just hides it so and now I got to find it again thanks a lot all right so now we've got it ha I did it again that's alright we're still waiting for builds to happen all right simulator is up did I get a breakpoint hit what did i do what did i do all right so I did this did this let me run this again live coding and it's fine if something will always go wrong all right I have a breakpoint I can click through click through how's my constructor not getting called did I not knew the right view controller up thank you thank you all right now we have a new class let me press play again all right there's a bug that has been fixed and sometimes if you don't rebuild it does not redeploy it has been fixed let me make sure that works so why you should always be on stable or the latest alpha not old stale alphas now you're kidding me all right delete this guy oh I've got two of them how does it know which one to do it doesn't yes all right we're gonna go all out let's reset you simulator go away let's run it again breakpoint hit how come on always way okay well that is starting I'm gonna write a little bit more code we'll come and check our sanity check in a minute because it has to work so all right so as I said we're gonna write some normal code it's very common to go in and download some Jason so we're going to first start out is I like to have a different style pad like to do everything with a refresh style so we can tell it's refresh when it needs to so we'll do public async task connect and then we will say oh not just that refresh and it's like I have no idea what to do with you control option space for all those in xamarin studio and normally it's right if I I don't know why that didn't work awesome telling you shortcuts that don't always work it normally brings you straight to that okay so we'll do a NATO refresh task I want to tell it to eight and we're just going to tell it to refresh and so I'm going to do bar client equals new HTTP and I haven't added the reference yet but you are all used to doing okay system net HTTP beautiful I can now go wrong hockey do that perfect client dot download straight get string someone is calling me right now cancel that before it pops up on my screen okay we're going to get string async and I know I messed up my clipboard that's why I have sublime perfect all right so we now have out inside the quotes are amazing API from Dropbox who's used our Dropbox for an API yeah suggests we've done that okay I'm the only one that dirty I guess it's awesome alright so we're just gonna say our jason equals await that it's kind of nice you just need a little config file somewhere on some that's not going to use much okay so download this jason file and then the next thing i should also go add a package let's add the ever-popular new in soft jason and hope our Wi-Fi can i'm not even hard wired i am going crazy on this one so hopefully the Wi-Fi it worked perfect so now we can do newton soft jason-- jason-- convert deserialize object now i am also going to cheat again I love these little things that actually create my class for me so I pasted my little URL and Jason utils comm and it created my object so yes alright throw that in there perfect I used to use Jason to c-sharp but it started doing I didn't like the way it was doing things and the casing and whatnot so I like this one more now all right Jason utils calm alright alright so we're going to tell us to deserialize an object and we're gonna say it's a list of if I need it what was that so we'll do a list of song okay I don't need there we go and oh that's totally wrong yes yes there we go now I can do Jason all right and we'll save our objects equals perfect all right let me right click fix using collections I'm gonna change this a little bit since when we have a list of stuff we can use UI tableview controller perfect that's that alright we've written some code let's make let's see if our simulator is willing to work with us now I don't have breakpoints but hey it talked to us yes and it came from the constructor and there he is so line 19 is true it is the main thread so and yes line 19 perfect okay so you know line 19 is the main thread things are working we're in good shape alright so we have an object we're going to download that let's just do list what am I thinking song sorry I will just do that so we don't have to deal with no reference options and we'll also just say you know what let's just say songs equals this this note for this table view dot reload data reload data perfect all right now unfortunately we're not gonna have any UI because I haven't done anything so override rows in section we can now just say return songs question mark dot count override get cell sorry oh yes thank you so equals table V equals helps alright table viewed all right perfect DEQ we should totally pasted this stuff at a time all right table view cell perfect new your table you sell you a table you there it is I saw it salt thing it's gone table view cell style there it is okay so we'll just say it's a default now we'll go subtitle subtitles are fun let's hit an enter so you guys can keep seeing what I'm doing and cell yeh return so of our song equals songs index path row alright so dot title or no dot text label dot text equals sorry is there a question or comment you can all follow I'm not going too fast here with writing the boring code text equals song artist alright so we should now see something except I have not called refresh so we won't so let's first tie this thing in override view did a peer whenever the strip thing appears we're going to reload our data just so that way it's nice and responsive we'll call refresh it's going to complain that I'm not asynchronously waiting this so I am going to say async Foyt which are evil but once in a while necessary if you want to know why there's an awesome blog post on it from why can't I remember his name now at github huh no I'm trying to I can't reveal hacked it has an awesome write-up on this all right so I'll put a breakpoint here and we'll put a breakpoint here so that way we know what's happening and we'll know when the data comes back and I'm refighting am relying on Wi-Fi so let's hope it works hey yes all right let's press play again and we have data perfect no yes thank you thank you let's see what happens though so this is code all probably written something identical to that now did anyone notice I have a major bug in performance flow on this anyone a lot of it is on the main thread not all of it close all right let's player what thread of my game so let's first jump here and we're going to break some of this up to make it at will break up later so let's say what thread am i alright well throw in here what thread am i and actually as I would highly recommend you actually save your clients and reuse them a lot of people dispose these that's very inefficient and you're supposed to save these guys just for kicks all right so we're not going to create the client each time now what we can do is say what thread am i what thread am i all right now for the game guys let's see who knows what's going on what was that all right line 32 are we on the main thread or the background thread everyone who says main thread raise your hand everyone who says background thread raise your hand all right what about let's get away free fresh all right so we have an async task we are instantly saying what thread am i and you guys were all right everyone said main thread and it says true really hard to read but that is true all right so we just jumped to the background came back what thread of my background thread a couple of people raising main thread alright we're on the main thread let's check yes main thread why because a weight will always bring you back to the thread that called it like I said we want to make sure we're always thinking main thread main thread main thread okay so that means what am I doing here how big is this JSON file let me hover over it really quick and if I start scrolling through this I can get to the bottom you know it's still loading the loader it still doesn't even finish loading as much as I scroll down I still have seen the bottom of this this is a lot of Jason and now like you will notice we are on the main thread so I just parsed all that on the main thread yes I'm doing a similar switch cheating that looked instant but if you're doing this on an iPhone 4 or 4s you can have about a five second lockup and one thing I like to do what I'm having people play at this data says I then switch it out for a 15 bags ass on file and instantly will you're completely locked up like now go find your bug and they're like oh it's just the Jason files two bags like nope you're doing it on the main thread alright so there's a few ways to fix this one thing we can do is let's start breaking this out and a couple different things to make it nice and clean we will do a sync task string now won't do a string we'll just do a list song and then we'll do is parse JSON perfect alright so now let's move this here actually we'll say return this perfect right and you'd actually pass that JSON n all right now I start changing if you think so everyone went through training is played with configurator wait we'll get to that in a second but let's just say first songs equals parse Jason all right now oh I should have wait that shouldn't I and I also have to put in the Jason that helps alright that's done now we can throw in this other method what thread am i and we'll know what thread we are now we already know this wouldn't be on the main thread even though it's a call in this is an async task which is returning this but unfortunately that does not let us leave the main thread and we can do a sanity check if we want it's right we'll come back to other things trust me it's the main thread okay you'll see it it'll fire eventually alright so that is the main thread now some quick easy ways to fix this I see is a way task dot run and we're actually going to put this in some braces that way we can do this and put some console dot write lines in there in cocoon all right perfect and actually why is this yelling at me a sync task oh that should go I didn't return yet I just haven't gotten that far that was next alright ah monkey where am I actually there we go undo redo best place to find your place back in your code alright so let's say what thread am I so we should have line 42 fire which is going to say we're on our main thread as I promised you and let's hope I'm not lying all right what thread am i this one press next said true this one should say false yes we finally found a false guys let me zoom in false 44 all right we know it is on the background threads we're getting somewhere now let's actually step back and play with something else one more thing we'll do songs equals and we're going to bring this back to the main thread so that's one way of fixing it we'll do this twice we'll keep it in here you should do every operation twice just to make sure it works all right so oh floral there all right so we have what thread of mine now there's another cool thing called configure way configure way is awesome I can just go to this task which we already have and we're waiting it and I can say client target string async configure await and true or false I can say false which will tell it do not go back to the thread you started that's all it means stay on the thread that that task you ran is running on now let's run and see what happens if I do this so now if I do 3034 we have a wet thread am i I want to start playing with things it's going to get a little tricky alright so inside of here it's downloading JSON we should probably save that strings we want to keep downloading it so what thread of my this one what thread are we front or back you are thread who thinks you are thread a couple UI threads background thread a lot of you are scared to answer guys come on all right this is background thread why it should be background thread we're assuming that whatever library we are using is going on the background thread you can verify these by doing this little method but since this is the HTTP client I'm going to trust that Microsoft the guys in the dotnet group knew what they were doing and truly went to the background when they downloaded this string so now if I press play we're on the background 34 is background perfect all right so now if I press play again this is fun and now inside my async one this one this is going to say front or back front thread or our UI thread anyone background thread all right yes since we were on the background thread it's not going to magically jump us back to the front all right so background thread is still false so I really didn't even need this task dot run now we could actually simplify things and not pollute the thread pool and not even deal with that stuff so what thread of my is gonna return back on the main thread and it's now complaining at me why am I getting a crash yeah I'm trying to update the UI from the background thread so easily I fixed my parsing issue but I totally screwed myself over and broke my app okay so let's go through and look at some other things to fix this and make it a little bit nicer okay so if we jump back into our view controller let's create some more methods everyone knows more methods is better your code is bigger and it looks like you know what you're doing um so we're going to add in a a new one and we're just going to call this one let's call this one download and parse so we're going to combine this why in the world do we need to have this happening all by itself over here so now I'm going to throw in here whoo that's awesome I press back and jump sing forward that is crazy I've found a new bug to file all right async task list song all right download songs perfect we put this in here and we could just return the songs or set it full return it's we're not being horrible people and will return that perfect now let's get rid of this right now this is where it starts getting fun and interesting so I have songs imma say oh wait download songs now want thread am I will put one here so I'm going to run this again all right line 41 main thread or background thread background thread main thread yes people are catching on main thread yes because we're learning this is good there's less and less getting wrong each time exciting I know I am totally changing the code every time to make sure you're paying attention that's true I am doing that I got it you got to pay attention what's the point of this talk if you don't pay attention all right so songs right now we're on the main thread main thread press play now this one should still be on the main thread we haven't done anything tricky right true main thread now remember line 42 you can't see it so let me not hot it again undo redo every time works great all right we're going to come over here hit enter so now you guys can see line 42 is the tricky one it has configure wait false all right so the compiler is going to lie and say it's line 33 but line 44 what thread is it background thread yes okay so we're on the background thread now this is where it gets interesting so line 44 is on the background thread we press play it says true I messed something up where I'm not breaking on the right spot it could be off because let's restart it since I hit that enter that totally confuses things let's try this one more time we'll move this breakpoint this one configure wait false 44 should be the background thread oh it was the print before I didn't press play again so we didn't actually see all right okay so this one should say false and it did yes it said false now download songs is called right here I threw a configur weight in there what is line 34 gonna do yeah okay everyone who says background thread raise your hand come on people don't be shy all right those of you on the main thread sorry guys main threads right so configure weight is only for the scope of that method um yeah because it was tricky so you start dealing with these things you're like wow which one is it in this case it is the background thread now as I mentioned before though configure weight can be tricky so right now if I press play again we are one more time true we're back on the main thread all right so let's do one other fun thing and see where we're at what if I say async actually let's undo this Jason thingy you don't like this let's stitch this stitch this ditch this perfect that is awesome now lead it half my code you know you're doing something good when you get to lead a lot of code so we'll throw this in here and where do I want to we are just going to okay I'm going to move some put around let's grab this guy again goodbye songs will download this thing and we are not going to configure weight on this one we want it to be back on the main thread so we're not confusing ourselves now what we will do is we will say not download song but parse JSON and Jason Smith prefers when you call it JSON because it's really confusing on the office when I would sing Jason this and Jason that so I try to remember to say JSON but I'm horrible at it alright oh wait I forgot something doc can figure a weight false so what does this tell us to do what is line 36 gonna say now all right let's run this and see all right so who thinks it's on the background thread all right who thinks it's on the main thread all right let's see hey breakpoints all over it did not like all that deleting code all right here we go moment of truth we are on the main thread why anyone know why yeah I didn't do anything all's I said it is an async task it's an async method no but I didn't do anything in here I just returned instantly so configure weight can be confusing because I was a horrible person and gave you a bad API I said it's a sink I'm returning a lid a task but I didn't I didn't I did it on the main thread so be careful don't always trust those methods but I would hopefully think you could trust the built-in dotnet ones and they'll all be nice to you not like I was and there we go we can continue back to this and go back a little bit more I go back too far no we're good here this is about where we want to be all right deleted that evil code sorry it's gone perfect this did the configure wait false all right so let's tie into this let's add a little bit more UI to this and let's play with this a little bit so it's a fun little pattern something that is always interesting we like our UI to be responsive we like to be able to have people to interact with things right so but right away we're telling to refresh as soon as you get to this page so let's do this dot navigation item dot write bar button item equals new UI bar button item we're going to call it a refresh ctrl + s comma e don't worry I'll make this smaller for new lines yeah so I'll make it smaller so you can't see it at all but let's go there now here we're just going to be lazy and just call our refresh we'll say it's async and we will be nice and await it ok a wait refresh now let's inside of our refresh let's add something that so we know what's going on so we will inside of here we will just say power not con static and refresh count equals zero first thing we'll do is just say refresh count plus plus refresh count - - alright so let's go into our what thread am i and we'll also throw in something new we don't care about the line anymore we will just say thread count take all thread when I come refresh count I was thinking thread count said refresh count alright refresh count and let's make this more obvious alright so now when I first start this and it's great that our Wi-Fi is nice and slow for this API because it we have time to go in there like any user of our app is like why don't I see anything we've all had that we're up to 14 threads now awesome it's going to happen re options are disabled the button but they don't even know you're refreshing so like why is this refresh disabled all right so let's play with something else let's change this a little bit and let's create once again more methods so async task refresh will do it a nice little lower case one that is private and we're going to move all this jazz into there alright we are also going to do something a little cooler it's a task refresh task okay a task is an object that's all it is it's nothing magical it's an object it has properties it's something that you can save we can interact with objects you're used to awaiting them it just returns a result but if you save the task rather than just awaiting it you can do cool things with it I'm actually going to make this function no longer async so I can now say if refresh tasks and they clap a lot of it I must not be doing good all right so if okay so if refresh task dot is completed question mark question mark true has anyone ever done that seen that syntax if something is null make it true all right it's perfect I promise all right refresh task equals refresh return refresh task all right anyone know what I just did there I see hands someone want to speak up correct so it's saying if refresh task is null we're just going to say true it's done or if it has completed so if I click to refresh once it's finished refreshing I need a new refresh so I can say refresh task equals refresh and now what's awesome and magical about this let's throw in one more console out right line will throw in a static and because static videos are way better refresh button count we're gonna do the same thing here and okay I do not like that indentation that looks ugly that we're going with it alright perfect refresh count so hold on which ones I've got too many refreshes all right - - there we go so now I can say right here actually we'll just say all right line finished refresh and had I done this with the other ones and that's actually we're not even care about the count who cares about the count well know what's going on all right so if we were doing it the other way these refreshes would have all happened at different times and drastically different times because we'd have been trying to download over this awesome Network draw that big old JSON file 15 times a lot of times like that's ridiculous especially if you start thinking there on cellular edge they're never going to see data but since we're saying oh wait refresh we can come into here and actually no I do want out but I want to output every time this thing increases so console dot write line I should undo caps-lock refresh button clicked so actually why am i doing indexes who does that alright so we'll do a refresh button count perfect all right so now it's going to print out whenever these things happen and we should go down here and grab some of our awesome ugly stuff so we can find it actually let's comment half this out so we can find it all right we don't need all of this we know how many times it's going to be refreshing refresh count will only ever be one and we will say and I can't spell refresh that is even better perfect let's run this and let's spam this button again so the Refresh count should instantly will see in our output will see we're refreshing you can't see excite deleted all the ugliness but if I click this a bunch of times we're seeing this happen and we're up to like 1213 but notice they all finish at the same time we never spun up any new threads our user had no idea we were already refreshing the database at that point we could have turned the spinner into a spinner icon or something but this is great when you have one style refresh multiple views would pull the Refresh on everything you have one task you will wait that same sync everywhere and all of them can await and at the same time everyone collapses it's awesome alright we do have time to play with one more little thing we are almost out of time but let's make this thing talk everything's better when your computer is talking to you so let's do navigation item dot Left bar button item equals new you might bar button item dot we'll say done so ask my hey I'll do that comma e perfect so we'll do a sync void and here we will say speak a sink Boyd why am i doing a sink food I apologize all right speak now for this we need to use the AV I'm going to steal I can't remember the name speech synthesiser yeah oh I try not to try not to cheat alright so far synth equals new AV speech synthesizer and it's not liking that I don't have that avfoundation perfect and now we can say synth the speaker it is begin I know utter and something about other and speak utterance new AV speech utterance I think the first one is text yes no yes so we'll say text perfect now with this stuff I hate callbacks I'm sorry callback so the go-to statements of today they're horrible and so many ApS have then the entire iOS API is nothing but callbacks and people like callbacks we have a sink and wait why would we deal with this so there is a did yeah but we do and I still see in dotnet events they're horrible they call so many memory leaks every memory every app I help fix memory leaks 90% of them are caused by event handlers event handlers are evil yes I said actions you can null them you can actually clear them out all right so you will just throw one of these things in here so when it's finished we get this callback how in the world am I going to wait this thing you can't however we can do some other things and I'm gonna cheat one last time don't look don't look all right there we go I just hate typing this thing out so pure laziness there yeah exactly I see okay so now what we will do is we will say delegate equals this so I'm saving in a sense of my event handler here not globally because globally is how you end up with memory leaks if you can get away with this this works great all right so now what we'll do is we'll de var TC s equals new task completion source who's ever used a task completion source awesome okay task completion sorts are great they're an easy way to make callbacks asynchronous because you don't want to do with callbacks just trust me on that all right so now what we can do here is we can say oh wait TCS done we've waited for it to finish wait what oh task thank you I was like wait a minute all right dot task so inside of here we will do TCS try set result true just to say hey we're done even though we're totally ignoring whether it's false or true or false and now what we can say and here is synth dot we didn't tie this in yet we will do did finish speaking utterance minus equals Dell and then right here since that did finish equals plus equals Dell check that out we have now subscribed and automatically unsubscribe to our event handler we can go into whole thing on what's causing issues with that and if you don't it runs into circular references and nothing gets disposed and you'll end up with like a hundred of these speaking things every time you talk so yes don't do it so if we unsubscribe these they can now be garbage collected so I have time to make this run and say hello and then we are time for questions if anyone has any alright so we'll say a wait speak everyone I have no idea if it's going to respect that that would be awesome if it does I don't think it will though all right so let's put an async here let's run this puppy what'd I do wrong what was that that should have been async there I just fell wrong didn't even notice all right so when tell it to speak utterance we should get this callback and then console dot write line we finished hope that'll work all right well we're waiting for Siri to talk to us is there any questions we're down to the five-minute mark if not I can keep coding or we can talk questions nothing either I did really good or really bad oh yes this right here the speaking thing I'm sure I'm going to zip this up and I'll tweet it to put it on Dropbox so I think I can get them to put it in the notes when they push the things live so this code sample we just did I will get live so yes patterns like this there's little drop my github I have a little toddler apps that my wife wanted to build so it like talks to the kids and it has this pattern in there but yes any other questions where are we back to this code no there we go all right so now when I click done it's going to speak to us and I have no sounds you're not going to hear it I told them I wasn't gonna use sound so it's alright it waited for it to finish before it happened which is great because now that entire AV speech synthesizers thing can be disposed and will go away calling disposed does not make it go away just so you know if you have things holding on to it even after calling dispose it will stay in memory and stuff from the OS side can be very heavy so any questions anymore if there's anyone raising your hand over there I cannot see you at all those lights are blinding so no all right well thank you everyone if you have anything else to ask me later you
Info
Channel: Xamarin Developers
Views: 16,079
Rating: undefined out of 5
Keywords: Build
Id: jgxJbshvCXQ
Channel Id: undefined
Length: 43min 34sec (2614 seconds)
Published: Wed May 04 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.