{"id":229585,"date":"2020-06-10T09:00:38","date_gmt":"2020-06-10T16:00:38","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/visualstudio\/?p=229585"},"modified":"2020-06-08T14:10:42","modified_gmt":"2020-06-08T21:10:42","slug":"how-do-i-think-about-async-code","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/visualstudio\/how-do-i-think-about-async-code\/","title":{"rendered":"How Do I Think About Async Code?!"},"content":{"rendered":"<p>Increasingly essential to writing responsive applications, asynchronous code is becoming more and more popular. Unfortunately, asynchronous programming adds an additional level of complexity to your code.\u00a0 As a result, understanding how this code even works can be tough no matter your experience level.\u00a0 Whether you\u2019re new to it or you just want a refresher, here is an intro to the world of asynchronous code!<\/p>\n<p>&nbsp;<\/p>\n<h4><strong>What is asynchronous code?<\/strong><\/h4>\n<p>Asynchronous (async) programming lets you execute a block of code without stopping (or <em>blocking<\/em>) the entire thread where the action is being executed. \u00a0A common myth about async code is that it improves performance, which isn\u2019t necessarily true.\u00a0 Instead, the major perk of async programming is that it increases the number of tasks (<em>throughput<\/em>) that can be executed concurrently without having to block the thread where these actions are taking place.<\/p>\n<p>You may think async code seems a little like multithreaded code.\u00a0 After all, many methods could be executing at the same time in both.\u00a0 In reality, async programming can be used together with singular or multithreaded applications.\u00a0 This means you can have a single-threaded async program, where one thread can run concurrent tasks.\u00a0 Conversely, you can also have a multi-threaded async application, where multiple threads can each run multiple concurrent tasks.<\/p>\n<p><strong>\u00a0<\/strong><\/p>\n<h4><strong>Why should I use async <\/strong><strong>code?\u00a0 Example please!<\/strong><\/h4>\n<p>To use an analogy to demonstrate async programming, consider the action of baking a cake. This action will be represented by a thread that is executing several steps (or <em>tasks), <\/em>as\u00a0illustrated in code below.\u00a0 This code is serviceable, and you will still have a yummy cake once the method is done executing.\u00a0 However, since all the code is <em>synchronous<\/em>, each line will run sequentially.\u00a0 In other words, you will be standing completely still while waiting for the oven to finish preheating.\u00a0 You could be making the batter for your cake in the meantime!<\/p>\n<p><figure id=\"attachment_229592\" aria-labelledby=\"figcaption_attachment_229592\" class=\"wp-caption aligncenter\" ><img decoding=\"async\" class=\"wp-image-229592 size-full\" src=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/SyncCake_Light.png\" alt=\"Synchronous MakeCake() function\" width=\"727\" height=\"351\" srcset=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/SyncCake_Light.png 727w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/SyncCake_Light-300x145.png 300w\" sizes=\"(max-width: 727px) 100vw, 727px\" \/><figcaption id=\"figcaption_attachment_229592\" class=\"wp-caption-text\"><em>Synchronous MakeCake() function<\/em><\/figcaption><\/figure><\/p>\n<p>&nbsp;<\/p>\n<p><figure id=\"attachment_229593\" aria-labelledby=\"figcaption_attachment_229593\" class=\"wp-caption aligncenter\" ><img decoding=\"async\" class=\"wp-image-229593 size-full\" src=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/SyncCake_Run.gif\" alt=\"Synchronous cake program\" width=\"1320\" height=\"718\" \/><figcaption id=\"figcaption_attachment_229593\" class=\"wp-caption-text\"><em>Synchronous cake program<\/em><\/figcaption><\/figure><\/p>\n<p>&nbsp;<\/p>\n<p>In real life, you typically want to multitask by making the batter while the oven preheats or making the icing while the cake is baking.\u00a0 Doing this increases your productivity and allows you to bake the cake much faster. This is where asynchronous code comes in handy!\u00a0 By making our existing code asynchronous, we can perform more actions to pass the time even while we are <em>awaiting <\/em>a <em>task <\/em>like baking the cake in the oven to complete. To do this, we modified our code to include a new function called <em>PassTheTime.<\/em> This code saves a task&#8217;s state, starts running another synchronous or asynchronous function, and retrieves the saved task&#8217;s value when it\u2019s actually needed.<\/p>\n<p><figure id=\"attachment_229589\" aria-labelledby=\"figcaption_attachment_229589\" class=\"wp-caption alignnone\" ><img decoding=\"async\" class=\"wp-image-229589 size-full\" src=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/AsyncCake_Light.png\" alt=\"Asynchronous MakeCake() function\" width=\"1389\" height=\"567\" srcset=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/AsyncCake_Light.png 1389w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/AsyncCake_Light-300x122.png 300w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/AsyncCake_Light-1024x418.png 1024w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/AsyncCake_Light-768x314.png 768w\" sizes=\"(max-width: 1389px) 100vw, 1389px\" \/><figcaption id=\"figcaption_attachment_229589\" class=\"wp-caption-text\"><em>Asynchronous MakeCake() function<\/em><\/figcaption><\/figure><\/p>\n<p>&nbsp;<\/p>\n<p><figure id=\"attachment_229590\" aria-labelledby=\"figcaption_attachment_229590\" class=\"wp-caption alignnone\" ><img decoding=\"async\" class=\"wp-image-229590 size-full\" src=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/AsyncCake_Run.gif\" alt=\"Image AsyncCake Run\" width=\"1320\" height=\"718\" \/><figcaption id=\"figcaption_attachment_229590\" class=\"wp-caption-text\"><em>Asynchronous cake program<\/em><\/figcaption><\/figure><\/p>\n<p>&nbsp;<\/p>\n<p>When compared to the synchronous MakeCake method that lacks a <em>PassTheTime<\/em> function call, MakeCakeAsync manages to complete more tasks without blocking the thread and shortens the time it takes to execute the whole method.<\/p>\n<p><figure id=\"attachment_229587\" aria-labelledby=\"figcaption_attachment_229587\" class=\"wp-caption alignnone\" ><img decoding=\"async\" class=\"size-full wp-image-229587\" src=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/Async_vs_Sync.gif\" alt=\"Async versus sync program comparison\" width=\"1320\" height=\"718\" \/><figcaption id=\"figcaption_attachment_229587\" class=\"wp-caption-text\"><em>Async versus sync program comparison<\/em><\/figcaption><\/figure><\/p>\n<p>&nbsp;<\/p>\n<h4><strong>How do I write async code in .NET?<\/strong><\/h4>\n<p>Thankfully, C# makes it a \u201cpiece of cake\u201d to write asynchronous code with the <em><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.threading.tasks.task?view=netframework-4.8\">Task<\/a> <\/em>type and the <em><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/keywords\/async\">await<\/a> <\/em>and <em>async <\/em>keywords.\u00a0 The <em>Task <\/em>type tells the caller about the eventual return value type. It also indicates that other actions can execute while the caller method is being processed.\u00a0 The <em>async <\/em>keyword enables the <em>await <\/em>keyword, which lets the compiler know that we\u2019ll need the return value of the function, but not right away.\u00a0 As a result, we don\u2019t need to block the call and can continue running other tasks until the awaited value is needed.\u00a0 An async method will initially run synchronously until it hits an <em>await<\/em> keyword. This is when the asynchronous execution will begin.<\/p>\n<p><strong>\u00a0<\/strong><\/p>\n<h4><strong>I just learned about async <\/strong><strong>code!\u00a0 Now what?<\/strong><\/h4>\n<p>While using async code to bake a cake is great, there are plenty of other real-life applications to use asynchronous code.\u00a0 Two of the most common examples include:<\/p>\n<ul>\n<li><strong>Programs using HTTP requests<\/strong> \u2013 Depending on the request, HTTP calls can take a long time to fully process. Using async code can let you perform other work while waiting for the server to respond.<\/li>\n<\/ul>\n<p><figure id=\"attachment_229594\" aria-labelledby=\"figcaption_attachment_229594\" class=\"wp-caption aligncenter\" ><img decoding=\"async\" class=\"size-full wp-image-229594\" src=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/HTTPCallExample.png\" alt=\"HTTP GET request example\" width=\"735\" height=\"420\" srcset=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/HTTPCallExample.png 735w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/HTTPCallExample-300x171.png 300w\" sizes=\"(max-width: 735px) 100vw, 735px\" \/><figcaption id=\"figcaption_attachment_229594\" class=\"wp-caption-text\"><em>HTTP GET request example<\/em><\/figcaption><\/figure><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li><strong><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/keywords\/async#example\">Programs using UI elements<\/a><\/strong> \u2013 WPF apps or any apps using buttons, textboxes, and other UX assets lend themselves well to async implementation. For instance, a WPF app taking in a file to be parsed may take a while.\u00a0 By making this action async, you can still interact with the UI without having the app completely freeze as you wait for the function to complete.<\/li>\n<\/ul>\n<p>Now that you know the basics of asynchronous programming, it\u2019s time to improve on it!\u00a0 There are a lot of secret do\u2019s and don\u2019ts when writing solid async code.\u00a0 For a great resource that explores these tips and tricks, check out <a href=\"https:\/\/github.com\/davidfowl\/AspNetCoreDiagnosticScenarios\/blob\/master\/AsyncGuidance.md\">David Fowler\u2019s post on async programming<\/a>.<\/p>\n<p>Like all code, there will come a time where you\u2019ll need to diagnose bugs in your async program.\u00a0 To learn how to debug your async code in Visual Studio, tune in for an upcoming blog post\u2026<\/p>\n<p>Side note: And no, I did not use the cake analogy just because I&#8217;ve been doing a lot of baking recently. \ud83d\ude09<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-229595 size-medium\" src=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/Cupcake-291x300.jpg\" alt=\"Red velvet cupcake\" width=\"291\" height=\"300\" srcset=\"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/Cupcake-291x300.jpg 291w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/Cupcake-992x1024.jpg 992w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/Cupcake-768x793.jpg 768w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/Cupcake-1488x1536.jpg 1488w, https:\/\/devblogs.microsoft.com\/visualstudio\/wp-content\/uploads\/sites\/4\/2020\/06\/Cupcake-scaled.jpg 1984w\" sizes=\"(max-width: 291px) 100vw, 291px\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>What&#8217;s asynchronous code?  When and why should you use it?  Check out this introduction to asynchronous code and how you can apply it to your future programs!<\/p>\n","protected":false},"author":651,"featured_media":229623,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[155],"tags":[237,6398,6399,5,9,287,12,475],"class_list":["post-229585","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-visual-studio","tag-net","tag-async","tag-asynchronous","tag-csharp","tag-debug","tag-tips-and-tricks","tag-visual-studio","tag-visual-studio-2019"],"acf":[],"blog_post_summary":"<p>What&#8217;s asynchronous code?  When and why should you use it?  Check out this introduction to asynchronous code and how you can apply it to your future programs!<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/posts\/229585","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/users\/651"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/comments?post=229585"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/posts\/229585\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/media\/229623"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/media?parent=229585"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/categories?post=229585"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/visualstudio\/wp-json\/wp\/v2\/tags?post=229585"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}