We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Async C# 5.0 - Patters For Real World Use

00:00

Formale Metadaten

Titel
Async C# 5.0 - Patters For Real World Use
Serientitel
Anzahl der Teile
170
Autor
Lizenz
CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben
Identifikatoren
Herausgeber
Erscheinungsjahr
Sprache

Inhaltliche Metadaten

Fachgebiet
Genre
Abstract
The new Async features come along with the very useful WhenAll and WhenAny methods to execute sets of tasks. We will delve into how these work, the effect of exceptions within any individual task and cancellation. This leads to the creation of common patterns such as Redundancy, Interleaving, Throttling and Early Bailout. Given time we'll also get to peek at progress reporting, something that provides the feedback to add further sophistication to these common patterns. Expect overviews of the patterns, followed by lots of code samples so get the latest Visual Studio 2012 RC installed ready for action.
3
Vorschaubild
59:06
71
112
127
130
ProgrammbibliothekFramework <Informatik>KommutativgesetzVisuelles SystemExogene VariableTermSystemaufrufKartesische KoordinatenSoftwareServerInformationGamecontrollerPunktMini-DiscDienst <Informatik>BildschirmfensterBitGüte der AnpassungTaskGewicht <Ausgleichsrechnung>Coxeter-GruppeInterface <Schaltung>GefrierenLastKonvexe HülleLeistung <Physik>Gerichteter GraphSichtenkonzeptFramework <Informatik>App <Programm>Bildgebendes VerfahrenPhysikalisches SystemTwitter <Softwareplattform>BildverstehenSondierungTotal <Mathematik>Klasse <Mathematik>Wort <Informatik>ProgrammierungMomentenproblemInformationsspeicherungNichtlinearer OperatorMultiplikationsoperatorCoprozessorRoutingBefehlsprozessorMultiplikationParallelrechnerFitnessfunktionZweiComputeranimation
ProgrammierungCodeFeuchteleitungKontrollstrukturOperations ResearchVorzeichen <Mathematik>Analytische FortsetzungTaskOvalParametersystemFunktion <Mathematik>AusnahmebehandlungVollständigkeitInformationStichprobeFramework <Informatik>Mechanismus-Design-TheorieTaskCodeWeb ServicesElektronische PublikationProgrammbibliothekBitSoftwareTypentheorieCompilerGeradeFestplatteLastLeistung <Physik>ThreadBenutzerbeteiligungFunktion <Mathematik>Klassische PhysikProzess <Informatik>RechenschieberServerPunktStichprobenumfangQuick-SortBildschirmmaskeParallele SchnittstelleBildschirmfensterInnerer PunktURLKontrollstrukturComputerspielGrundsätze ordnungsmäßiger DatenverarbeitungWort <Informatik>HilfesystemEreignishorizontEin-AusgabeProgrammiergerätStellenringVideokonferenzMomentenproblemElementargeometriePunktwolkeSystemaufrufFahne <Mathematik>MathematikSoftwareentwicklerDreieckMAPSchedulingAusnahmebehandlungGewicht <Ausgleichsrechnung>GamecontrollerResultanteEinsLesen <Datenverarbeitung>Gerichteter GraphObjekt <Kategorie>ParametersystemKommunikationsdesignKlasse <Mathematik>SoftwaretestArithmetische FolgeProgrammierungSchaltwerkDatenbankEndliche ModelltheorieNichtlinearer OperatorInformationFortsetzung <Mathematik>
Framework <Informatik>StichprobeFormation <Mathematik>Pi <Zahl>Offene MengeSchnelltasteDemo <Programm>MP3SynchronisierungKrümmungsmaßBildschirmmaskeCodeDatentypMini-DiscBitElektronische PublikationFormation <Mathematik>URLMP3SoftwareentwicklerDreieckFreewareSchreib-Lese-KopfDemo <Programm>CodeWeg <Topologie>DigitalisierungKommunikationsdesignMultiplikationsoperatorGesetz <Physik>PaarvergleichGeradeEinfügungsdämpfungDateiformatWeb SiteComputeranimation
StapeldateiProzess <Informatik>SchaltnetzWort <Informatik>LastStapeldateiKombinatorikTaskMultiplikationsoperatorZahlenbereichGerichteter GraphE-MailSoftwareentwicklerArithmetisches Mittel
Weg <Topologie>Mini-DiscElektronische PublikationBildschirmmaskeSichtenkonzeptPrognoseverfahrenPhysikalisches SystemVerzeichnisdienstExistenzsatzOvalZeichenketteHochdruckTaskMenütechnikRechenwerkStichprobeStreaming <Kommunikationstechnik>QuellcodeEin-AusgabeElektronische PublikationGewicht <Ausgleichsrechnung>QuellcodeMultiplikationsoperatorBitÜberlagerung <Mathematik>TaskApp <Programm>Prozess <Informatik>HypermediaStichprobenumfangMailing-ListeTypentheorieDemo <Programm>VersionsverwaltungVarianzMP3NeuroinformatikCodePunktFlächeninhaltLastSoftwareentwicklerArithmetisches MittelEinsp-BlockBildschirmmaskeSpielkonsoleBildschirmfensterKeller <Informatik>Physikalisches SystemKlassische PhysikPufferüberlaufStreaming <Kommunikationstechnik>Message-PassingSystemplattformInformationsüberlastungMicrosoft dot netGamecontrollerZeichenketteMehrrechnersystemFormation <Mathematik>SkalarproduktGerichteter GraphBenutzeroberflächeEinfache GenauigkeitHilfesystemLie-GruppeZahlenbereichQuaderWald <Graphentheorie>Wort <Informatik>Computeranimation
MenütechnikElektronische PublikationStreaming <Kommunikationstechnik>QuellcodeOffene MengeZeichenketteSichtenkonzeptRechenwerkOvalSpielkonsoleZählenIndexberechnungTaskData MiningPrognoseverfahrenSpeicherabzugGammafunktionMailing-ListeWeg <Topologie>StichprobeMini-DiscKonfigurationsraumTaskOpen SourceElektronische PublikationATMZeiger <Informatik>TypentheorieMailing-ListeBitZeichenketteArithmetische FolgeGrenzschichtablösungQuellcodeObjekt <Kategorie>MehrkernprozessorFormation <Mathematik>MP3SchnelltasteWeg <Topologie>VektorpotenzialOffene MengeStreaming <Kommunikationstechnik>Framework <Informatik>SchaltnetzSpielkonsoleLastInformationBildschirmfensterMultiplikationsoperatorGewicht <Ausgleichsrechnung>SoftwareschwachstelleGerichteter GraphBitrateGamecontrollerBaum <Mathematik>BrowserSpeicherabzugComputeranimation
StichprobeWeg <Topologie>SichtenkonzeptKonfigurationsraumStellenringInklusion <Mathematik>MenütechnikWurm <Informatik>Mini-DiscDemo <Programm>MehrrechnersystemBildschirmfensterLemma <Logik>R-ParitätPROMSigma-AlgebraSLAM-VerfahrenLokales MinimumElektronische PublikationQuellcodeMultiplikationsoperatorMehrrechnersystemMaschinenschreibenAudiodateiKontrollstrukturSynchronisierungRechter WinkelGeradeGewicht <Ausgleichsrechnung>BitKontextbezogenes SystemGerichteter GraphCodeFlächeninhaltAnalogieschlussHash-AlgorithmusThreadFormation <Mathematik>Computeranimation
BefehlsprozessorRechnernetzElektronische PublikationMP3Prozess <Informatik>ThreadMultiplikationsoperatorMustersprachePunktGamecontrollerWeb ServicesRechter WinkelTransaktionBitLastMailing-ListePhysikalisches SystemSchaltnetzVerkehrsinformationAdressraumNeue MedienDatensatzComputerspielBrowserOrdnung <Mathematik>MaschinencodeDienst <Informatik>AudiodateiGemeinsamer SpeicherGüte der AnpassungDifferenteKonstruktor <Informatik>Elektronische PublikationRohdatenMP3ThreadEuler-WinkelCodeServerKonstanteSpeicherabzugBefehlsprozessorWeg <Topologie>
Weg <Topologie>InterleavingOvalSichtenkonzeptPrognoseverfahrenGebäude <Mathematik>HIP <Kommunikationsprotokoll>Demo <Programm>Quick-SortCAN-BusMAPZählenSpielkonsoleIndexberechnungTaskSteuerwerkZeichenketteMenütechnikKrümmungsmaßRechenwerkWechselseitige InformationFaltung <Mathematik>W3C-StandardStellenringHill-DifferentialgleichungNabel <Mathematik>KommunikationsdesignMehrrechnersystemBildschirmfensterCodeElektronische PublikationGeradePunktDatenparallelitätLoopMailing-ListeGebäude <Mathematik>TaskWeg <Topologie>MultiplikationsoperatorTypentheorieBitMomentenproblemDatensatzMAPLastIntegralTermAusnahmebehandlungRechter WinkelStapeldateiDateiverwaltungPhysikalisches SystemProzess <Informatik>HilfesystemEinfache GenauigkeitGrundsätze ordnungsmäßiger DatenverarbeitungKonstruktor <Informatik>Arithmetische FolgeGamecontrollerSpiegelung <Mathematik>Trennschärfe <Statistik>FestplatteDateiformatEinsOrdnung <Mathematik>CASE <Informatik>Befehl <Informatik>Komplex <Algebra>ZeichenketteKonstanteSpieltheorieDifferenteBenutzerschnittstellenverwaltungssystemMinimalgradZweiBildschirmmaskeGefrierenEreignishorizontGüte der AnpassungVersionsverwaltungMenütechnikZahlenbereichServerComputeranimation
RelationentheorieDienst <Informatik>SichtenkonzeptOffice-PaketAusnahmebehandlungTaskWort <Informatik>ElementargeometrieRelationentheorieComputeranimation
SichtenkonzeptWechselseitige InformationProgrammRechenwerkMenütechnikBildschirmfensterDemo <Programm>MehrrechnersystemSummierbarkeitStellenringKonfigurationsraumMagnettrommelspeicherSLAM-VerfahrenSpezialrechnerDean-ZahlBewegungsunschärfeSchlussregelDualitätstheorieToken-RingFinite-Elemente-MethodeQuellcodeMailing-ListeElektronische PublikationStreaming <Kommunikationstechnik>ZeichenketteQuellcodeInstantiierungGerichteter GraphTransaktionMehrrechnersystemSystemaufrufGemeinsamer SpeicherElektronische PublikationSoftwareentwicklerTranslation <Mathematik>Open SourceBitVersionsverwaltungTaskWeg <Topologie>CodeCAN-BusTextbausteinInformationsüberlastungKeller <Informatik>Web SiteZahlenbereichToken-RingSpieltheorieQuelle <Physik>Schnitt <Mathematik>Microsoft dot netPunktRechter WinkelParallele SchnittstelleSynchronisierungDebuggingBildschirmfensterGeradeSichtenkonzeptTypentheorieProgrammbibliothekZeichenketteDatensatzComputeranimation
ZeichenketteTaskToken-RingElektronische PublikationStreaming <Kommunikationstechnik>QuellcodeMenütechnikSichtenkonzeptGammafunktionPortscannerDemo <Programm>SLAM-VerfahrenZählenOvalStellenringSummierbarkeitKreisringSimulationDoS-AttackeElektronische PublikationCodeToken-RingPhysikalisches SystemQuellcodeAusnahmebehandlungZeiger <Informatik>LoopTaskProgrammbibliothekMicrosoft dot netDatenbankStreaming <Kommunikationstechnik>ThreadGruppenoperationCASE <Informatik>DatenverwaltungMultiplikationsoperatorProzess <Informatik>BitPunktParallele SchnittstelleProgrammierungMailing-ListeSichtenkonzeptUnrundheitBildschirmsymbolFormation <Mathematik>Computeranimation
Web-SeiteBrowserProzess <Informatik>TaskWeb-SeiteLastOrdnung <Mathematik>Cross-site scriptingBildgebendes VerfahrenBandmatrixMultiplikationsoperatorElektronische PublikationSoftwareTaskBrowserMetropolitan area networkProzess <Informatik>SkriptspracheComputeranimation
SichtenkonzeptZählenTaskMessage-PassingArchitektur <Informatik>Mini-DiscGebäude <Mathematik>OvalHolographischer SpeicherHIP <Kommunikationsprotokoll>Demo <Programm>KommunikationsdesignWeg <Topologie>SimulationFormation <Mathematik>PunktMultiplikationsoperatorWeg <Topologie>TaskFamilie <Mathematik>LastProzess <Informatik>Elektronische PublikationGewicht <Ausgleichsrechnung>CASE <Informatik>Protokoll <Datenverarbeitungssystem>Inhalt <Mathematik>AudiodateiFiletransferprotokollBefehlsprozessorDatenparallelitätComputeranimation
TaskAusnahmebehandlungWeg <Topologie>SoftwareentwicklerFormation <Mathematik>Prozess <Informatik>InterleavingFamilie <Mathematik>CodeElektronische PublikationPunktDatensatzDesign by ContractLesen <Datenverarbeitung>Nominalskaliertes MerkmalCASE <Informatik>
FeuchtigkeitGebäude <Mathematik>TaskMini-DiscZählenMessage-PassingZeichenketteWeg <Topologie>StellenringLokales MinimumDemo <Programm>CodeSpieltheorieSystemaufrufDynamisches RAMCoxeter-GruppeLemma <Logik>VideokonferenzTaupunktVerhandlungs-InformationssystemTermCOMWeg <Topologie>Elektronische PublikationHash-AlgorithmusTaskLastZahlenbereichToken-RingRandomisierungMultiplikationsoperatorGleitendes MittelValiditätGebäude <Mathematik>Computeranimation
RechenschieberCodeAusnahmebehandlungTaskFamilie <Mathematik>ThreadRechenschieberWeb logWeg <Topologie>Twitter <Softwareplattform>Prozess <Informatik>Keller <Informatik>Web-SeiteVorzeichen <Mathematik>InternetworkingCodeGerichteter GraphPunktServerGarbentheorieComputerspielEinfügungsdämpfungElektronischer ProgrammführerHilfesystemDatenflussMultiplikationsoperatorMicrosoft dot netVollständigkeitBildschirmfensterSoftwareentwicklerLastVirtuelle MaschineZweiRepository <Informatik>AnwendungsdienstanbieterMP3Parallele SchnittstelleMusterspracheGewicht <Ausgleichsrechnung>Coprozessor
Transkript: Englisch(automatisch erzeugt)
Everyone hear me? At the back? Good. It's a very full room. I thought I was hidden on the back of this thing and no one would know where I was and I'd have an easy time. It's nice of you all to be here. From my first time at NDC and so far it's been
great. Just out of interest, on the keynote, remember there was a discussion about a mobile phone being an interface to a bigger device and being a route to it. I'm not checking tweets while I present. I'm using this to control PowerPoint. So a Windows phone can happily control PowerPoint and show you all the speaker notes and allow you to jump around
the presentation without worrying about it while looking at tweets. No, really. So hopefully you all know what we're here for. You've read the abstract. The abstract was copied from an old conference because it suggested you had VS 2012 RC installed, which
is a horrendous thing as I read it this morning and went, what a silly thing to leave in. This is specifically, there was a white paper when async await was emerging as a technology in the kind of almost CTP days. Steven Taub from Microsoft wrote a white paper. It
was based asynchronously or tap. Who knows about that white paper? Wow. So that's good because if you have read it, studied it and implemented it, you need to leave. Because
that's what this talk is basically about. But like a lot of white papers, people don't read them. They need someone to talk about them or go to them or promote them. Which is a real shame because writing those white papers is quite hard and they are quite informative. So what this is about is I hope who's used async await? There, good. That's good because
I don't need to go into a long intro. I will do a little bit of intro about what it is. But we're talking about using async await to do more than just make your UI responsive. Which is generally where it's kind of sold. If you've written a WinForms app or you've
written a WPF app and you want to do some background task, going off to a website, going off to disk, async await allows you to have that responsive UI. Your UI doesn't freeze. I've got an ad for the company I work for, which I'll mention in a second. So who am I? I'm Liam Wesley. I work as an application architect at huddle, which
is an old startup in London. I get to work on a bike. 6,500 kilometers a year. So I no longer fit in skinny jeans. I'll tell you that now. When I'm not working or commuting, I'm playing. My youngest daughter, my eldest, and my dad at a farm I went to at Easter.
It's great. As an idea of entrepreneurship, the farmers on this farm visit, they decided they would use the plastic tubs they get feed for animals in, shove wheels on them, join them together and drag them around on a tractor and charge you for doing it. That's great.
I think that's quite cool. So at huddle, we create a server-based system. So we're all about server, not about UI. That's why this appeals to me more. It's not going to be a UI-type talk, although there's a UI to demo. So what is async? A load of people know it. It came in .NET 4.5. So the aim was we want something that makes asynchronous
programming much easier because there was a vision that everyone would be writing in Windows RT. Never mind. And that was important because that required this kind of asynchronous
operation to be there because the kind of devices we're aiming at, you don't want a phone to suddenly go, no, I'm making a call to the network. I'll just stop doing anything on the interface while I go and do it. That's what the old Windows mobile phones used to do. And they locked up regularly. So we don't want that. So in it came. Then
they brought it out for BCL. So for anyone who can't implement .NET 4.5, and there are servers out there where a tech ops guy will not allow you to put 4.5 on it, you can put it on a .NET 4 server quite happily by using the BCL. So that's a good move.
This is something you can backport. Still need VS 2012, but you can put it on an old server that isn't even 4.5, which is quite cool. And that's how they allowed it to go on Windows Phone and Silverlight apps. So the key goals of what async is there
for. And that's it, basically. We don't want anything to stall on a background task. A network call. A disk IO call. Something like that. Something where actually it's not CPU intensive. It's IO intensive. So your processor could happily do stuff, only it's waiting for bytes off a disk. And your whole application is grinding to a
halt. Now, that could be your server-based application that's making multiple requests for data from other services. And it's stalling and not giving data back to the user because it's waiting for this IO to complete. In terms of Windows runtime, they were aiming at anything over 50 milliseconds should be done asynchronously. Which means in the
4.5 framework, there's so much more stuff that is asynchronous enabled, ready for you to use awake, which is cool. Not everything you'd expect, but quite a lot. The other one is, there's loads of people out there who really know how to write synchronous code.
It would be nice if it looked like, say, synchronous code. Except we just shimmy in this bit of background processing on the side. And that's with the other goal for awake async. Make the code readable. Make it actually go for the business requirement without actually all the cruft that is normally associated with background threads. You
know, how do I then transfer it back to the thread I was running on? How do I marshal things from a background thread to a UI thread so that a Windows form can be updated for a background thread? All that kind of thing. The aim was to get rid of that so your life was made much easier. That's the goal for async-await. There's
two key words I keep saying async-await. Async. You put it on a method, and that says, hey, somewhere in the middle of this method, we're going to have a control flow that's going to await something to happen asynchronously in the background. That's it. So if you've used await, you might have put it in the middle of a method, compiled,
and the compiler says, you can't do that. You haven't put the word async on this method. So you put the async on the method. Interestingly, although they were trying to maintain it's going to be simple, it's going to look like your synchronous code, the moment you start using async-await, everything seems to have async written down on the entire call stack because you're going to have to do that because they keep all calling
each other. So you are going to have to do some changes. But basically, that async is a flag to the compiler saying this thing is going to await something inside. And then you have await, which is what you use that says, hey, I know this is going to take ages. Go off and do it. When it's finished, yell at me, come back, tell
me you finished, and then we can carry on. And that allows you to free up all that processing power. So when I get that thing off the network, come back to me and we'll carry on working with it. In the meantime, I can go and do other stuff. I can let the user choose other things on a form, do other stuff. At some point, you're going to have to think in a threaded background processing world of the user
can't do everything they might want to do while that background process is happening because at some point, you need the result back. So you still have issues that you have to think about. But it's so much easier, so much easier for anyone writing a UI to handle background threading. So that's the basic
ones. Where you would have had a method in the old synchronous days that returned void, you returned task. So they took that from the task parallel library. It was already there. It's really useful because you can do cancellation, you can check progress, you can do all sorts of nice things on the task object. And where you would have had a return value
of, say, int, you return task of type int. And that way, you can hand values back from your methods. You might have had a lot of, God help me, out parameters, which you shouldn't really do. Let's be honest. It's not the nice thing to do to a person consuming your API. Create a class,
create a struct, return that. It's much easier for them to deal with. But if you have output parameters, you really are going to have to now wrap it in a class and return it as one whole value. It is possible to have an async method that returns void. That's void. Please, please, please, please don't do that in your own code. It is there purely
to allow it to be used for things like event handlers on forms and such like. You are not meant to implement that. If you implement that, you're saying, I don't care about the poor sort who's going to use this method. I'm not going to tell them anything about it as it progresses. Cancel it, monitor it, anything. That's the kind of thing
that if you were given that API, you would be cursing the programmer who developed that. No, no, no to voids. As I said, task T and task, really great. We can find out how they're performing. We can do cancellation. They use the task parallel
library's cancellation mechanism to easily allow you to cancel tasks all at once without you having to run around a little array of tasks, find out all the tasks that you've got, go canceling them down the line. You can go cancel a whole lot and off it goes. That's great. The whole point of this is
you're going to be able to concentrate on the business problem and let someone else deal with threading. That's enough PowerPoint slide. We're going to get to code. As a sample code, I don't know if anyone's seen asynchronous talks before. In
general, they'd have gone for maybe a web server. Classic example, I'm going to go to a web server. I'm going to give it a geographic location or a post code. I want it to look up some data, geo information, tell me which town I'm near, something like that. It's great because it goes off to a web service in the cloud and it's really good when you give a talk at a conference or a user thing to rely on public Wi-Fi to
get your data. It's not. You could all be downloading videos at the moment and I'd have no access whatsoever. The other thing is I could do a local web service. I could have made an iOS web service. Instead, what we're going to do is we're going to have some sample data that's
simply going to be file copying. That's all we're going to do, which is an IO-bound activity on a hard disk. Could be a network call, could be a hard disk operation, could be a SQL operation, but we're doing copies. So we've got sample data, which is not to be used with simple data, which
is Mark Rendell's library for accessing databases, who's also talking at this conference. Now, everyone knows that developers are great at graphic design. I had to adjust this map. I'll tell you now. Does anyone know what this big triangle is? The UK. So we've got the UK here. This
is Ireland. That's the Isle of Wight, which has a festival on it. We still own this bit over here as well in the UK. No, I think that's the silly Isles. I think the Fulton Islands is a bit further away. And I had to add this bit in a bit of a hurry last night. So important bit.
Obviously, I'm boring. I live in London. And we've come to Oslo. But in Sheffield, there's a band called Silence. Not the Silence, Silence. It's just pain in the backside. But you can go to that web address and you can download a
single, a four-track single. And the real advantage of this is it's royalty-free. I haven't put it in GitHub because all this code is in GitHub because I don't own the copyright for the music. But you can go and download it for free. And you can download the MP3 file. Or the FLAC or the OGBORBIS or the AAC files. And that is our
sample data. We are going to muck around with some music tracks with the advantage that when we finish copying music tracks, we can play them. So I'm relying on my taste in music, which is kind of indie guitar. And
hopefully it won't be too offensive. It's not rude or anything. It just may be very derivative in your viewpoint. It's not jazz, though, so don't worry. So we've got these files. AAC, FLAC, MP3. The important bit about this, if you know about audio formats, I used to work for a digital download company. So we mucked around
with transcoding files quite a lot. Is that FLAC files are quite big. Because they're lossless. So when you do a FLAC file of a music track, they're 30 megs, 38 megs for like a four-minute track. In comparison, the MP3 file
is more like 10 megs, 13 megs, that kind of, you know, era. When you go to kind of AAC format, which is what iTunes uses, it squishes it a lot harder, gets even lower. So it's about half that. The really nice bit about this is if you have files that effectively represent
the same data, but are different sizes, then you can do a demo where the first file wins. And that might be the smallest file, because it takes less time to copy. Now, obviously, for anyone musically inclined, those smaller files, they're lossy. They're not as good quality.
But the fact that Beats headphones have managed to sell for billions of dollars to Apple means no one really cares about quality of music. So it's fine. All right? Because I used to have a really old hi-fi, and it had a button called loudness. And that's what Beats headphones are. A loudness button on your head. So I shouldn't
have worked in music industry too much. So, yes, that's our sample data. So the first example we're going to do, so, in a sync-await, in that white paper, there's things called combinator methods, or combinatory methods,
it's an awful word. But basically, they take a load of stuff you want to do in a bag and throw them at something and do them all at the same time. So this is where we're going to get the bonus. So this is when you first looked at a way to sync, I don't know if anyone has seen when all and when any. Yeah? And you look at it and you go, when all, I can see why I
use that. When any, kind of. Once you've read the white paper, you find that when any is a really useful one and when all is a really dull thing. But when all is useful, because you might want to do everything. And you want to send a load of tasks off, and you need all of them to finish. So just think, sending off emails, sending off a load of
insurance numbers, and you want to batch them because you know it's going to take time for them all to come back, and you want to get the employee details. So that's when all. So to add to the confirmation that developers can't do design, and I
don't do WPF either, we have, you can barely tell that I used to write in VB. It's a Windows form that's gray with lots of tabs and buttons, which is the classic VB type app. But it's the easiest way to show you how it's working, because it has
the least amount of code. And we get to play something, we get to put a bit of album art over here. We get to use an active X control to play music, even though it's a .NET app. And we've got a little console output and we've got a button to tell you what to do, and we can just go through all the examples. Behind all this,
really simple. When it starts up, it's going to clear out a temporary folder. So we've got a, in that user interface, we'll just run it up. We've got a source folder. And that happens to be in my source code for where my app's living. And that's got a
load of those sample files, the ones I showed you earlier that were all different sizes. That points to there. This very nicely points to your user area in a temp area, so we're not littering the computer with loads of files all over the place. And all it's going to do is copy from the source folder to the destination folder. That's all its aim is.
And just to make sure, it does things like clears all the files from the folder, clears down and sets the temporary folder path so you could override it. It's not very exciting. Every time we run one of these things, we're going to clear the temp folder out. We're going to clear the console so it doesn't have any messages again. And then we're going to kind of clear what was playing on the media player.
So we're just resetting the system every time we click the button. So let's do a sample of when all. So first thing we've got to do is get a list of files to copy. We've got some helper
methods. I'm not going to type everything out. You'll be glad to know. So one of the things we're going to do is we're going to go to our source folder and we're going to recurse through all the folders underneath and we're going to get all the files that we need to copy. All the AAC, all the
FLAC, all the MP3 and all the OGG files. We're also going to get the cover art. And because each of them had its cover art and they're all the same, we're just going to mute that and just take one copy of the cover art so we don't copy it four times. So that's quite simple. We're just going to get a list of all these files to copy. The next thing we're going to
do is we're going to say, right, what I want to do is do lots of tasks. So I'm going to create a list of a load of tasks. Remember the task type T? So whatever I'm going to call as my task is going to return a string back. Because that allows me to know when I copy a file, where is it now?
Where is the file destination going to be? So I get a string back saying here's the path to where the file is that I just copied. We're going to create that new list.
Obviously it's squiggling to tell me I got three sharper for you. I've had real flames about using VAR with people. So for a demo it makes much more sense to not use VAR so that people understand where
you were coming from. So we are going for every file name we're going to do something. So we've got that list of file names and we're going to do something with them. So we're going to go through all of them and what we're going to do is copy them. Now, you would think
if you were going to copy a file, using .NET framework, you go system.io.file copy. You think great, I'll just go to file copy and job's done. Make it call the async version of it. If only they'd made an async
version of file copying because they didn't. What they did make was an async version of copying from one stream to another. It's fine. So I kind of understand why they did this. They wanted you to think if you're going async, block sizes, things like that.
If you did a file copy async, what does that mean? That means copy it? Does it mean big blocks, small blocks? There's absolutely zero input. You'd have to start overloading it. The more you overload this stuff, the less it works when it goes to another platform which has a limited version of .NET framework. You might as well go to the base classes, wrap it and make your own little file copy.
It doesn't take a long time. It's, you know, a bit of Googling, a bit of Stack Overflow. Job's a good one. 20 minutes, job done. All we're going to do is we take a source path for a file. We're going to copy it to a destination. There's a bit about the UI progress details and progress bar controls so that it
looks pretty for you. Basically, what we do is we open a source stream with file mode open. We then create, open a destination stream. Just like browsers, when they download, we're going to call it .TMP. We're going to copy it. And this is the important bit. We're doing an await on copy to async. We can
do that because we wrote async at the top of our method. And by convention, we wrote async at the end of the method name to let everyone know it was async even though you've already decorated with async and they know it's async. There you are. It's in the guidelines and it is quite useful because when you glance in an object browser, it's really easy to see what's going to go async. And we just copy it.
4,096 bytes at a time. And then at the very end, when we're finished copying it and we've updated our UI so it looks nice, we're going to rename the file from .TMP to the final file name. Because we finished copying it, it's successfully copied, we can now give it its original file
name. And then we return that file name so that whoever called us knows exactly where the file has been copied to. So that's pretty much it. So the way we do that, we had that list of tasks that we were going to execute. So all we do is we add a new
task. Which is just the method name. That method that we were going to call. Because it returns, well, it says it returns string but it's the async modifier so what it returns this task of type string so it all fits into the framework. So we are going to take one of the
file names out of the array. That's the first thing we do. We then do a bit of funky stuff with path combine. I don't know if any of you still do string searches for slashes and
UNC. Don't. Please use path combine. It does it all for you. It's really wonderful and it will get you out of a lot of trouble. So what I can do is just say hey, give me the file name that I had as a source. And shove it on
this path. So it says give me this path, give the file name from that source separate from its path and join them back together and now we've got a destination file name. So it's so trivial it's hard to believe. We aren't doing any fancy UI stuff so I can set all that to null null true which are magic values. It should all work. I'm just checking
what the squiggle is. Probably null reference. There you are. Null reference. So what we're going to do is run it. So we can just go wait. When all which is all we were trying to do was go right. We are going to take all those tasks,
all those copies of files that we've carefully built up because adding them to the list didn't get them going. All it did was say I now have the potential to run this and copy a file. You have to give it a kick to make it get going. So we give it a kick with when all. Now this actually handily returns an array
of strings. Because it works out. It's a type task string. So every one of these tasks will return a string which represents the file that was copied. So we can just because we've got all of them running, we can just put them all in one string array,
bang, we've got a list of strings. Because we've done that, we can now play a track. So if we have actually copied these files correctly, we can look in the files that are copied, get the first thing, first file name
that ends with .mp3. The joys of a US keyboard and an English layout. And the other thing we will do is do some album art because everyone knows
that having music with no album art looks horrible on any UI. Have I got that right? Let's see if it builds.
It's hard to believe it's a quad core with 16 gig of RAM. But there you are. So let's run it. Go back to that old-fashioned world. So, when all. So we're going to copy all these files. We should see a load of information coming through here in our
console window. Let's move it up a bit and then you can see it. While we're doing that, we'll also just have a look at the folder. Not the source folder. I don't want that. So let's simplify it. We've seen where the source files are. Let's have a look in here. Right. So when we run this, we should
start seeing files appear here. This is my user's temp area. We'll see files starting to appear. And this will prove that we're actually copying all these files at the same time. So even though we fired them all off with one line of code, we will be copying them
in the background. And I've still managed to move the UI around a little bit. They're all temp files and they gradually all become the real file when they're finished copying. And then eventually plays the music. So that just managed to queue up. Now you can't hear me. That managed to queue up 17 file copies.
Actually, more than that. 21 file copies because there were MD5 hash files as well. And copy them all simultaneously to that folder without me having to think about it. While I still have a UI I can play with, I could prove that I have a UI I can play with because if I click that button twice while I'm running it, it will go and break because I've
forgotten to disable the button. So async await does not stop you from shooting yourself in the foot. Which apparently is the analogy everyone's using today. So my phrase here is, it's a bit dull, it just copies music files, which is all it does. But has anyone written
code that can copy 20, 30 files in the background themselves using threads? Was it fun? No. And it came back to the UI and could update the UI and tell you as it went along that it was doing stuff as well, which is horrible thing to have to do
to kind of touch both threads. And you've got synchronization context and background threads and marshaling to do with. So, you know, this is not a bad thing at all. So that's a lovely quick win on when all. And you can imagine that there's loads of situations where you want to do multiple things. They submit a report,
there's four things to go off to the data, but you can fire them all off. If they're not bound by transaction, even better. Because obviously, if you do a transaction across them, it gets a bit harder to do that kind of multi-threaded approach. But surely, I believe now we may not be. We may be in a world where people use Microsoft Distributed Transaction
Coordinator still. However, I'm in a world that's eventually consistent, and I'm quite happy with it being eventually consistent. So, I don't mind slightly if things appear slightly out of order, as long as they get there in the end. You know. You can't take that attitude to cooking. If you put the wrong things in it, wrong order in cooking,
it tends to bugger up the meal. But in programming, a lot of solutions can be done out of order. It's quite fine. So, we go on to another combinator. we have when any. Now, when any is, hey, I've got a load of stuff. I've got all these things to do. When any
of them finish, any, just one, come back, and tell me, and come back to me, and then I can do shit. I can do stuff. So, here, you first thing you think is, it's a first win. So, it's the kind of thing where you say, I've got a post code.
Go find addresses. I'll use four different services on web services. One of them comes back. That's fine by me. I'll use that as my list of addresses, and I don't care about the others. You might use it in finance for share prices, things like that, and come back first. think, eh, it's fine. The advantage is,
it's much easier to use when. It's, there are much more better ways of using when any. So, there's, these are the patterns that were in Steven Taib's white paper. So, this, I'm, seriously, I think when you see that I've used the exact same naming of a constant. That's how much I've lifted Steven
Taib. get throttling. people use FTP clients. Who's used Filezilla? How many files can it download at the same time? Does it kind of stop at some point? At about eight,
maybe ten. You can set it. But normally you don't actually, your browser doesn't download 500 files at the same time either. It's not normally a great idea to do that. So, at some point you start throttling. one of the examples we had is we're in a digital media company. The record company's
send us raw music files. Really good quality. CD quality. WAV files. we're converting them over. If they send us ten albums and they've got ten, fifteen tracks each, I could throw 150 MP3 encodes onto an eight core system. If I do that at
the same time with no throttling and no thread control, I tell you now that server's going to fall over. At the very least, when you remote desktop to it to see what's happening you can't because there's no CPU to allow you to get on that remote desktop. loads of systems in life we have to throttle.
So let's see how we can do that really easily with the when any construct. So and then we will use code snippets. But it's good to see how you build up this code. And how
it's kind of uses these metaphors for a list of tasks all that kind of thing. So we're going to copy a bit from previously anyway. We're going to get that list of file names to copy. Equally, I'm going to do something funky.
Is I'm going to sort. Now this is simple. Bit of Lambda-y stuff. We're going to sort the file names so that they're in order. So all the track ones come together. All the track twos come together. All the track threes because we had them all in format before. And this allows us to see them being copied
in order. And we can compare strings.
We're going to have a constant. because we're going to throttle, we're going to have a concurrency level. going to say we're only going to do four things at once. We know we had 21 files, but we're only going to do four at a time and then we'll batch them up.
And that allows other things to happen. know someone else maybe using my hard drive. Just maybe. Especially if it's a server. we're doing the same kind of thing. We're creating a new task. It's called copy tasks.
Certainly not that. So you can see how we're building from where we went from when all differences. We're now going to set a concurrency level. So the thing is we're not going to loop
through because we can't loop through. Because we're not going for I'm going to run every file in the system. What we're going to say is I'm going to set up the initial tasks. There may be less than
our concurrency level. could be that it's a you know sometimes when you get an album from a record company. It could be a single track download. There aren't four things to do in the background. You only have one thing. So we've got to make sure we don't kind of go too far. But otherwise we're pretty much going to use the
same code we did before. The only thing we're going to do that makes it nicer is we're going to have some progress bars because it's nice to see these files just being updated.
I remember the days in VB6, God help me, where you had indexed controls on webforms and it was much easier to deal with it. this one I've had to actually do a bit of reflection and jiggery pokery or select
case statement I think I put in to get round it, which is a bit of a pain. So that will just mean that while we're copying these four files you'll see starting done starting done starting done and it makes it much more obvious what's happening on the UI to give you a feel for how you might actually
allow people to see what's happening but realistically that's just a setup so yeah that looks a bit complex but what all we're doing is pre-loading four tasks into our collection of tasks what we're then saying is we're going to start executing and this go
this is where oh that's how you use when any that's how you're going to use it so the thing we're going to play this time because i wanted you to obviously hear all the different tracks off the four track album
is we're going to play a different track we're going to play track four realistically we're going to play the last black track to prove that you can actually play a black track so copy task is completed
and the real point is i've missed a line this is what i am going to nick a bit of code for you because i can just see myself over running and we really want to see all the types
so what we're going to say is oh yep i have to go one down though i need to show you the one i let the top so what list of
all the tasks and we're saying if there is still stuff to do and that's what this line is if we still have some tasks that need processing because we have tasks in this list then wait for the first one to come back the one the moment you
say when any you start running all those tasks in the background now there's only four in there because we made sure we only put four in at the very start we then say if it completed because it could fault it could have other things happen so we're going to check it's completed then we remove it from our
list of tasks it's quite cool this this list of tasks because we know it's finished now so we don't need anymore we then say hey so we had a copy task list of four tasks four file names one of them's finished we remove that task and get rid of it
we then get look to see if we've got any more files to copy we have got more files to copy create a new task
in three we still got file names we add another one and go back to four so that's what we did and then we say by the way if it's flack record
it so that we can play this very last track which we know is a flat file and then when we get that we're going to play that audio track and it was last flat file copied it's
the one we're going to use just strip that off and that should compile so what we're looking at is we start with 21 files that we're going to copy we put four of them in an array we get one of them to finish we put one back finishes put one back finishes
put one back this happens quite a lot until we've got all 21 files have been processed into at least what got in there then it goes three so what does that look like in terms of what our file system is going to do
well what's going to happen is we should get four temp files at a time so we haven't got that big list of all these temp files we're now only copying four at a time and they're gradually going through
and possibly stopping dead which is unusual how much on it that's an exception about to fire that's interesting right
really interesting thing is when i was playing with this the other day because we now have git integration inside of vs 2013 it was watching files and locking them which was great because he hadn't versioned them but it got a handle on them let's have another go so we're copying four at a time they should be appearing four at a time
and there you are and then it finally starts playing the last file so that's throttling that's very quickly allowing you to say hey i only want four things to happen at once now yes
was that a pretty amount of code realistically no but it wasn't a lot of code it's not hard to put that in a load of this code to be honest is to do with ui stuff and it's much more simple if you didn't have the ui really so this is a really fantastically easy way to do that situation where you're going to throttle
we're going to do four five six things at once and we don't want any more than that to happen if any of those tasks by the way faulted had an exception it would come back we could handle that exception throw another task in and keep going in if you wanted to just process everything
the other thing that happens is someone normally one of the questions is when the first one comes back what if while you're waiting and then you do in a way when any one of those tasks that was still in there has finished well it just pulls the next one off that's finished straight away it doesn't even kind of really wait for them to get going it just kind of goes right
okay have that have that so solves all that kind of thing uh redundancy now this is the one where you thought this is how when any was always going to work it's the first one wins and comes back so you know that's really good because that's stock price it's a geo lookup that kind of thing this is much easier i mean much easier
let's just close down a bit and i'm still running get out the debugger so when any first wins let's copy that in
and reopen the file so what's behind this button well we're going to put this behind this button this is a world of cut and paste because i was too lazy to simplify it
all right i just cut and paste and do the third track flack aac og m4a don't care just copy them just copy them and the first one that comes through we're fine just go with it because this is the one where i don't care what the quality is i just would like to get it as fast as possible so that's um which bit torrent site has managed to download the latest episode
of game of thrones that's the one that'll do that kind of thing so if we run that we should see a nice let it get going i should see that folder get emptied
gonna do a simple thing where we go when any first wins copies all the files starts playing one of them there now the interesting bit about this if you've noticed is how many files did it
copy four and that's interesting because i didn't care i just wanted the first one but it kind of carried on doing all the tasks for me so now there's two views on this is
i don't want it to carry on doing the task i'd like it to cancel all the other tasks and get rid of them the other one is in finance when you're looking at share prices is i want all the tasks to complete when i'm looking for share price from a market maker because we pay them for looking up a share price and if we don't complete the call we can't record the transaction
number put it in the audit trail and then reconcile the accounts so this is not stupid that it allows all the tasks to finish but it may not be what you want but that's great or it's fine because remember i said because they're using the task parallel library
and because we are returning task of typing task of type string we have cancellation support built in right so this is going to make life easy so all we need to do is that boilerplate
code that we did have we're going to do a cancellation token source i am going to increase the you're right sorry about that because i closed the window it reset
to 100 so we have a cancellation token source you notice we've got red lines all over this and that's because we haven't actually designed copy file sync to support cancellation
cancellation token source is not a magic bullet i cannot just say i have a cancellation token source whoa put it on this task i'll cancel and it will do everything for me it's not going to you need the async method that you're going to call to support cancellation that's quite important so i said earlier that once you've used async once it tends to litter your code
down the code call stack once you've used a cancellation token it will probably litter your code with cancellation tokens being passed all the way down the call stack um the point i once had a developer say i'll copy that bit of coding i ought to do that
so we have copy file async we have the version that and it's just an overload we're going to have so don't worry it will go bigger in a second
so there's the async the normal version and here's the one with cancellation and we'll walk through that and tidy it up please tidy up yes right so one developer said i'd like to just throw a cancellation token go cancel and everything just stops and i said
that's great the dotnet framework must be getting really intelligent because it knows whether you're in the middle of doing something serious like a transaction or halfway opening a file and knows how to clean it all up and knows better than you what you intended to do and the problem is it doesn't it has no idea what to do if you get cancelled because it can't it doesn't know
what you're doing it didn't know realistically what the aim of that file copy is it might not matter if you stop halfway through it might be quite critical if you stop halfway through so really you can't do that so that's why you have this concept of cancellation tokens that you hand to your async methods and the async method when it's cancelled says this is what i do when
i get cancelled these are the actions i have to take if you didn't use a cancellation token you could probably get the thread process and just kill it but that's like task manager finishing outlook which you have to do regularly um but you know it's one of those things you don't
want to do if you write your own code you can build all this in so we pass in a cancellation token cancellation tokens are really simple things they are in the task parallel library you have a cancellation token source you create that new that immediately creates a singleton of a cancellation token that's thread safe that you can hand to multiple threads
so that's good the reason it works is because the source stream copy to async supports a cancellation token if someone in the dotnet framework wrote an async method that doesn't support cancellation you're stuffed right at this point for the await side of things you can spot
it at other points you could spot it in your loop but realistically this isn't a loop that's the copy that's happening so fortunately they support cancellation and how does cancellation work it throws an exception in your code all right so that may horrify you that it throws exceptions
exceptions are like nulls in databases the older you get the more you like them and the more you think they're a good thing and not a bad thing all right just because it makes it slightly harder to program doesn't mean they're bad all right importantly what we're going to do
well unimportantly we fiddle with the ui to make it look pretty but more importantly we are going to check if we have a temp file and if we have a temp file because we've just copied that file it was in the middle of copying this file we'll delete it so this is where if it just
killed the process we'd have tmp files all over the place which is really messy so this cleans it up for us so this is basically going to copy four files the first one wins and it will cancel the rest and they won't get copied and even if they're halfway through
it will clean up i should have checked that that built properly and it did so when any first so it's first wins and it should clean up so we only have
one file at the end yes and there we are and if i run it again yeah i haven't cleared down the files properly that's annoying see this is the problem with async uh you better make sure
you're not still doing things in the background i will check that we do the cancellation yeah it should cancel all that down and there you are that was me when i copied that code in no one screamed you didn't clear down the previous run and then this is actually a valid um i kind
of you know it's never great when actually things don't go quite right but it's a good example of how you have to think about this in general you disable the button so you can't click it twice that's the easiest way of doing it that's not necessarily you know a nicer way is clearing it down stopping it playing and restarting it all so let's see that in action again
so now that's why i put all that protection code in so we can see it's got the og file again because that was the smallest so clearly that was going to win this is where it's not going to do it for me i'm trying to generate a very weird edge case that's hard on an ssd to
do because it keeps copying them really fast about it's about one in 20 times that's the what you will find if you click this enough and you have a system that's marginal and somehow can
get away with this they may have improved the compiling in 2013 from 2012 but i doubt it um what occasionally you get over here is you see the og file and the mp4 file because they're virtually the same size and when you hit the cancellation
in between you hitting the cancellation token to say hey cancel and it raising it it finished copying the file and our cancelled exception only deletes tmp files so that's an example you've got to start thinking we're multi-threaded this is a bit of
a pain at times so you have to be a bit defensive on how you do things like clear up like handle all this kind of stuff so but that's cool because we did first one one we deleted them all off and we saved on network bandwidth people were doing network bandwidth and
things like that into leaving um your browser does this all the time you know it does not download a web page one item at a time until you embed some javascript in your css page and it can really screw your page loads up i tell you now there's certain times when it will start
downloading one item at a time before it renders your page and you want to avoid that but in general if there's a load of images on a web page it will download them all in the background separately and it will start showing you to them showing them to you possibly out of order and the page has that little kind of dance after half a second where it looks like crap and
goes right that's what i was meant to look at now i've got the css file and then it's cached and it all looks fine the next time so that little jiggle so we can do that with when any we've got that ability to kind of do this into leaving so the idea here is we have some task
that we've got we have some task which is long running but we have some menial tasks that once a single task is finished we can execute like that so there's no point doing a wait on it
because it's really fast why await something that can execute in like 10 milliseconds no point might as well just do it so what we're doing is getting all those file names to copy again we're creating a load of tasks to copy going through doing this when any again it's this um concurrent thing is it no it isn't in this
we're just asking it to do it and what it's going to do is every time it's downloaded a file it's going to check the md5 md5 is just checks them so in the case of music files they give you an md5 generally so you can check that the music file delivered from warner brothers is actually
correct and that we've got the right content which is a nice thing to do because unbelievably ftp is not the most reliable protocol in the world at times and can get corrupted or they can copy the wrong files into a folder with the wrong md5 which is even more the problem
so interleaving we've got some heavy io process and all we're going to do is do these md5s in the meantime so while they were all copying we could do this md5 we didn't really hold much cpu time up we've managed to check these as we went along and we ended with a file music being
played and you think well that's kind of good you know interleaving but in my example i just gave what would happen if an md5 is incorrect you wouldn't want to carry on downloading so this is the real advantage of that interleaving is early bailout so if you are downloading 20 tracks
from an album from warner brothers to sell in your music online music shop if you have one track that isn't there that's corrupted you don't sell the album and there is virtually no point putting it through the encoding process if you haven't got the original file don't bother
um again a great developer an innocent young child who you know scott said but surely we could sell the 19 tracks that are okay um if you look at the legal contract that's it for a record company you don't go around selling the single tracks if you're meant to be selling the album that's a kind of joint deal that you get the album and you get the single tracks and you're really
meant to tell them if you haven't got the data and you're not meant to sell them separately so in that sense so um while in the real world it might be interesting to do that well in the theoretical world we could survive one of those tracks not arriving in the real world we want to stop and get out of there and the code for that's nice and easy because
you saw we had cancellation so we're building on that we had cancellation we had interleaving so now all we need to do is say hey if we get an invalid so this is a standard thing we're just doing we're interleaving but this time we're saying
if we are have an invalid md5 we are going to cancel all our tasks and stop copying files because we don't want this data it's dead to me so let's build that so it's quite nice
the cancellation was with first any that allowed us to clear up now we're using cancellation with interleaving that allows us to do early bailout um all this is using stuff if anyone had done the tpl this is quite familiar it's using tasks it's using cancellation tokens so what i can do is run that we're going to see a load of files come through
um clearly this is going to work i think because all the md5s are correct yep looks like yeah they're all valid so what i really need to do is edit one of these md5s so let's edit one if you ever wondered what an md5 looks like
it should be in here somewhere of course it's not let's go and get into the aac we're going to edit one of these md5s it's just a random hash of numbers we're going to edit one of them
Numbers and letters, we'll edit it. It now won't work. So we can look at that folder. So we are now going to do it and we should have a failure of an MD5 and we get to be played the track that had the problem so we can see what's wrong with it. And it should bail out and stop copying files for us.
What a shame. You got Rick rolls. Never mind. That is a pretty sackable offense for a speaker to still be Rick rolling people. But yeah, the keen eye amongst you there would see that I played audio track with a lowercase T,
not an uppercase T, and that goes to a method that lies and just plays. But that's great because we can actually cancel out and stop doing things because something went wrong. So resources for this talk. The parallel team blog, whenever they're doing something interesting,
they shove it up there and that's where you find out about white papers. That white paper is two and a half years old. Shame on you for not reading it because it actually is quite useful for this. And the BCL package is available as well for those with server, you know, OS server deployments that won't allow 4.5. Not that many now. I think we're gradually getting to the point where it is all on there.
But those BCLs actually help if you're doing Windows phone development and things like that, which aren't on 4.5. All the code and slides are available at GitHub, Westley L, search for the repo to do with async patterns.
Tomorrow, I'm doing actor, so there is two NDC Oslo repos up there. So if you want to get me on Twitter, it's Westley L. I promise I talk about drinking an IT on that, not food. I have Westley Jam for food and family stuff and gardening. So you do get a pure IT feed. You can email me at any point.
I'll mention huddle again because huddle pay me to do things like that. As in, they don't make me take holiday to come to a conference, which is quite cool of them. We have jobs, QA, devs. If you're going to go for a job at huddle, please talk to me first because there's a signing on bonus, clearly.
And I promise we will share a chunk of that Michelin-starred restaurant in London once you're through your preparation. So we will enjoy that bonus if it happens. And that's it. Any questions? Wow. Yes. Yes.
So the question is, should you be very careful about using a wait async on an IS server? Yes, you should. Because you cannot just run up lots of threads willy-nilly. The point about these threads that you've seen is there's no more thread than the processor that was running them.
These are IO completion in the background. Therefore, all the things you've seen today realistically run on one thread. That was the UI thread. So all it was doing was allowing the IO to complete in the background and sign up delegates, callbacks. That's quite safe.
Creating a load of threads from a thread pool, slamming them into a when all in the middle of an ASP.NET page is asking for trouble. Because you're going to have a hard job reconciling it, especially as the page lifetime means it disappears before you can clean up. And then you're all into that mess, that world of pain. So I think you were right to be warned about being cautious
about using a wait async liberally in your ASP.NET pages. Now this, as I said, is a good question because this is virtually single-threaded. If you want to do proper multi-threaded processing, you really need to come to a talk about the actor-based pattern tomorrow
on TPL data flow. And that's when we'll take code and actually make it run on multiple threads and actually have complicated pipelines of processing all with a handy NuGet package. And it makes certain things that you thought about a wait async, you go, this is much easier in data flow if you're doing that kind of processing.
So it would have been wonderful when we were doing MP3 encoding to have data flow because it would have made our life so much easier. So that's tomorrow. I think it's second talk of the day, and I'll be presenting on that. Okay? Another question?
There's a real myth, I would say, there's a myth that exceptions are really expensive in .NET.
Yeah, I know what you mean. When it throws an exception, your machine seems to grind to a halt as it dumps a stack trace out, builds it all, gets all the marshaling on it. Remember that exceptions are exceptional? They really shouldn't be happening that often. The cancellation exception is lightweight. It's not going to cause the damage you think it's going to cause.
And when you get exceptions out of tasks, they come as aggregate exceptions, so they all get bundled together. And virtually, it's the first exception generated that causes you the most grief. After that, it tends to be quite fast to do exceptions. And you're already in a situation where you're canceling it for a good reason. So the loss of time on that cancellation
has got to be less than the time of allowing all those tasks to flow through to completion. There must be some reason you're deciding to throw that. The other way of doing it is you can, if you want, monitor the cancellation token, spot if it says is canceled, and then cancel out on that. But if you're handing to a .net framework async method
with a cancellation token, it's going to throw an exception. And people will expect your code to throw an exception rather than just silently end. So, you know, it's one of those things, I'm afraid. What you'll find with the data flow is it doesn't throw cancellation exceptions.
It drains your tasks really nicely for you. So that actually doesn't throw exceptions. It handles it all internally, and it works really nicely on allowing jobs to complete that are multithreaded. Okay. Thank you very much.