<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dmitry  Zvenkov on Medium]]></title>
        <description><![CDATA[Stories by Dmitry  Zvenkov on Medium]]></description>
        <link>https://medium.com/@dmitryzvenkov?source=rss-f74fa1e517fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Zk3gfWZeMAvnkBwE.</url>
            <title>Stories by Dmitry  Zvenkov on Medium</title>
            <link>https://medium.com/@dmitryzvenkov?source=rss-f74fa1e517fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:56:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dmitryzvenkov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Clarifying async/await]]></title>
            <link>https://medium.com/@dmitryzvenkov/clarifying-async-await-f9e632fb0398?source=rss-f74fa1e517fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9e632fb0398</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[c-sharp-language]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dmitry  Zvenkov]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 18:51:52 GMT</pubDate>
            <atom:updated>2024-12-12T18:51:52.705Z</atom:updated>
            <content:encoded><![CDATA[<p>I often find myself reproducing and repeating the same simplified explanations of programming concepts over and over — either for fellow co-workers or even random tech people I come across. It becomes clear that, in accordance with the DRY principle, I should’ve started jotting down some of the points I keep repeating in a form I could easily refer to.</p><p>The topic of this particular write-up is the async/await syntax, which originated in C# (version 5 in 2012) and has since found its way into many other languages. Since Unity game development forms the core of my experience, the points below are focused on C# (including code samples). However, they are generic enough to be relevant for anyone working with C++, Node.js, or TypeScript.</p><p>This is a fairly high-level overview. The goal is to collect most of the important ideas rather than delve too deeply. I’m also not competing with manuals here — the assumption is that the reader is aware of async/await syntax basics and has probably used it before. The focus is on the ideas behind the feature.</p><h3><strong>What it is and what it is not</strong></h3><p>One common misconception is that async/await is “<em>something about threads</em>”. Or, even more likely, “<em>something about tasks that are something about threads</em>”. This makes it scary (if not, that’s suspicious), but luckily, it is not quite accurate. Both async/await and the Task Parallel Library are tools for asynchronous programming, while multithreading is just one mechanism that introduces asynchronous flows into a program.</p><p>Actually, it’s often not even the most relevant one. For example, Unity, and most game development engines like Unreal or Godot, and UI-enabled applications in general — are limiting what can be done outside of the “main thread.” But that does not mean that async/await is not applicable to them. Actually, I’d like to advocate for its usage.</p><p>To get clarity on where async/await actually sits, we’ll need to set up a certain basis of what asynchronous programming is about and then walk through the evolution of ideas about expressing it in a program. Trying to keep it simple, though.</p><h3>Cooperative and pre-emptive multitasking</h3><p>Ordinary ‘synchronous’ program notation assumes operations are executed in sequence, matching the way they are written in the listing. This is natural for sequential algorithms, but (just like people) programs may pursue several goals at the same time. For example, they may maintain a process of generating or processing data while presenting it to the user. In this case, we need to work on an ‘asynchronous’ program where notation somehow reflects several execution flows. The fact that you progress toward two goals doesn’t necessarily mean things happen in parallel. They may or may not. Consider a human analogy:</p><ul><li>A person may be walking while listening to a podcast — in parallel. In the computer world, this is referred to as <a href="https://en.wikipedia.org/wiki/Preemption_(computing)"><em>preemptive multitasking</em></a>, which usually takes the form of <em>threads</em>. From an application programming standpoint, threads appear to run in parallel, meaning that, by default, one cannot assume the timing of pieces of code running in different threads is somehow synchronized. If we dig deeper, we can say that the OS actually decides when to give processor time to particular threads, with regard to hardware capabilities and other existing workloads.</li><li>A person may also work on a work assignment and a personal memo, starting with the work-related write-up, then sending it for review and advancing the memo while waiting for input from a co-worker. In computing, this pattern is known as <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking"><em>cooperative multitasking</em></a>, and from an application perspective, it means there needs to be a special effort taken to designate points in the flow where the current task is switched. Given the love of game engines for their main thread and the fact that their flow is broken into ‘<em>frames</em>,’ this is actually a natural concept for games programming — we stick to a single thread implementing a loop, where every frame runs through all individual pieces of logic we want to advance and does a portion of work in each. This is how <em>coroutines </em>work in Unity (and in general).</li></ul><p>We delved into this bit of theory just to support the following simple statement: <strong>async/await as a language feature does not imply which asynchronosity mechanism is actually effective for particular task/job/piece of work.</strong> It can be running in a separate thread, postponed to be executed a few logical frames later, tied to the results of an operating system call that runs in parallel with our process, or even be actually instant (or synchronous). These and other options can be and are expressed by means of async/await syntax to help with asynchronous programming.</p><h3>What are our options</h3><h4><strong>Idea #1 — Callbacks</strong></h4><p>The need for asynchronous programming is natural so the first and most obvious way to express this has been around all the time — callbacks.</p><p>Let’s work out few code samples that illustrate them.</p><p>We might have some external part of the program implementing some asynchronous piece of work and yielding result:</p><pre>public interface ISomeAsynchronousCallbackAPI<br>{<br>  void DoSomeWorkAsynchronusly( <br>        System.Action&lt;ResultType&gt; callbackWithResultToExecuteWhenDone, <br>        System.Action&lt;Exception&gt; callbackOnException<br>      );<br>}</pre><p>Then as a ‘user’ we could run it like this:</p><pre>object _storedContext;<br>void UsageSampleWithNamedFunction(ISomeAsynchronousCallbackAPI api, object someContext)<br>{<br>  _storedContext = someContext;<br>  api.DoSomeWorkAsynchronusly(SomeWorkDoneCallback, SomeWorkFailedCallback);<br>}<br><br>void SomeWorkDoneCallback(ResultType result)<br>{<br>  //continue work given the result, and _storedContext<br>}<br><br>void SomeWorkFailedCallback(Exception exception)<br>{<br>  //do whatever&#39;s needed to recover from the failure, e.g. retry<br>}</pre><p>Or, if we try to be less verbose by using anonymous <em>lambdas</em>:</p><pre>void UsageSampleWithLambda(ISomeAsynchronousCallbackAPI api, object someContext)<br>{<br>  api.DoSomeWorkAsynchronously((result) =&gt;<br>    {<br>     //continue work given the result, and someContext<br>    },<br>    (exception) =&gt;<br>    {<br>     //do whatever&#39;s needed to recover from the failure, e.g. retry<br>    });<br>} </pre><p>These samples highlight two groups of problems related to the use of callbacks:</p><p>Boilerplate</p><ul><li>We introduced separate named functions for the callbacks, which are not useful by themselves but are only needed to arrange the asynchronous flow handling. We did this twice, assuming we also want to handle errors that might occur in the process. This is hard to type and even harder to read because the reader is forced to jump up and down in the listing losing focus.</li><li>We actually omitted a thing we might need: declaring a named type for the callback.</li><li><em>Continuation </em>(actions that follow up our asynchronous piece of work) needs some context, so we are introducing and managing member field(s) just for the sake of that.</li><li>We may have mitigated some of the boilerplate by using lambda functions and closures, but this is still a fairly convoluted write-up that doesn’t scale well and escalates the next point:</li></ul><p>Rigid control flow</p><ul><li>Asynchronous operations are rarely executed in isolation, more commonly they are chained into sequences.</li></ul><pre>RunAsyncOperation1( (result1) =&gt;<br>  {<br>   //use result1 to start operation2<br>   RunAsyncOperation2(result1, (result2) =&gt;<br>    {<br>     //use result2 to start operation3<br>     RunAsyncOperation3(result2, (result3) =&gt;<br>      {<br>       //use final result3 somehow<br>      });<br>    })<br>  });</pre><p>Now imagine we add few more layers plus adding error handling and retries into equation — that’d really blow up our codebase and lead to a situation known as “<em>callback hell</em>”</p><ul><li>Apart from chaining, we might want to implement more complex scenarios, like waiting for two things to finish running in parallel (we don’t know which is faster!) and then using the results of both in continuation. Remember, any of them may fail… I won’t even be typing that cumbersome code here; let’s search for better moves instead.</li></ul><h4><strong>Idea #2 — Task/Promise/Future</strong></h4><p>In the OOP world, there’s a natural way of making ‘things’ manageable and easy to operate with — that is, encapsulating them into an object. The <a href="https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization">RAII principle</a> or <a href="https://en.wikipedia.org/wiki/Command_pattern">Command pattern</a> are good examples of that. Applications of this idea in different languages are known as Promises, Futures or Tasks. Actually, there’s a bit of confusion and inconsistency in what exactly is called what in different contexts, but we’ll focus on the C# implementation of the idea — the <a href="https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl">Task Parallel Library, or TPL</a>.</p><p>If we make use of it, our asynchronous API shall start returning a Task. Note there’s a common but not very strict <a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model">convention to add an ‘Async’ suffix</a> to such functions.</p><pre>public interface ISomeAsynchronousTaskBasedAPI<br>{<br>  Task&lt;ResultType&gt; DoSomeWorkAsync();<br>}</pre><p>Now as a “user” we can use <em>ContinueWith </em>of the Task object to attach code we want to execute for once task completes successfully</p><pre>RunOperation1Async()<br>.ContinueWith(task1 =&gt; RunOperation2Async(task1.Result)).Unwrap()<br>.ContinueWith(task2 =&gt; RunOperation3Async(task2.Result)).Unwrap()<br>.ContinueWith(task3 =&gt;<br>      {<br>        //do something with task3.Result<br>      });</pre><p>The fundamental difference from the callbacks-based sample above is that there’s no nesting involved now. Instead, each ContinueWith is given a Task object and produces a new Task object that encapsulates the work of the original plus some continuation, possibly also asynchronous.</p><p>This opens vast capabilities for advanced manipulation of control flow:</p><ul><li>We can store such an object or pass it to another routine, structuring and decoupling our code path.</li><li>We can access the status of the Task to see if it’s been completed already (<em>.IsCompleted</em>) or access the exception if there was any (<em>.Exception</em>).</li><li>We can also easily stop the execution of our control flow (current thread) until the Task yields a result (<em>Wait()</em> or <em>.Result</em>).</li></ul><p>The next sample shows how we could schedule some work to be done once all tasks are complete (assuming they run independently)</p><pre>Task.WhenAll(RunOperation1Async(), <br>             RunOperation2Async(), <br>             RunOperation3Async())<br> .ContinueWith(taskWithAllResults =&gt;<br>    {<br>        //do something with taskWithAllResults.Result<br>        //containing array of all results of all tasks<br>    });</pre><p>Think about how much boilerplate code we’d have to write to manage these parallel tasks if they weren’t encapsulated in a convenient Task object — tracking completion, storing results, and setting up loops for waiting and checking</p><h4><strong>Idea #3 — async/await syntax</strong></h4><p>With the introduction of the TPL, we gained many tools for manipulating asynchronous control flow. However, the common scenario of chaining several pieces of code around asynchronous work still feels clumsy. We’re forced to break our asynchronous flow into discrete async operations interspersed with sequential synchronous parts and wrap those into lambdas.</p><p>Let’s step back and look at our callbacks-based sample once again:</p><pre>RunAsyncOperation1( (result1) =&gt;<br>    {<br>      //use result1 somehow then start operation2<br>      RunAsyncOperation2(result1, (result2) =&gt;<br>          {<br>            //use result2 somehow then start operation3<br>            RunAsyncOperation3(result2, (result3) =&gt;<br>                {<br>                 //do something with result3<br>                });<br>          })<br>    });</pre><p>What’s really happening here is that we’re wrapping each consecutive logical part of the flow into a lambda and passing it as a callback to the async operation. This is in fact a purely mechanical code manipulation. What if it could be automated? <strong><em>await</em> does exactly that!</strong></p><p>Here is how it would look like:</p><pre>public async Task MyFlow()<br>{<br>  var result1 = await RunOperation1Async();<br>  //use result1 somehow then run next operation<br>  var result2 = await RunOperation2Async(result1);<br>  //use result2 somehow then run next operation<br>  var result3 = await RunOperation3Async(result2);<br>  //do something with result3<br>}</pre><p>It’s easy to see that our code is effectively unwrapped or flattened back into a sequence of commands, just in the way we’re used to. It is often said that compiler generates as ‘state machine’ out of this sequence under the hood, which is true but could be more confusing rather explanatory. Thinking of it as an unwrapped sequence of callbacks might provide a clearer and more intuitive understanding.</p><p>It’s easy to see that our code is effectively unwrapped or flattened back into a sequence of commands, just in the way we’re used to. It is often said that compiler generates as ‘<em>state machine</em>’ out of this sequence under the hood, which is true but could be more confusing rather explanatory. <strong>Thinking of it as an unwrapped sequence of callbacks might provide a clearer and more intuitive understanding.</strong></p><p>Worth noting that we need to mark for the compiler that a particular function needs this ‘magic’ applied, and <strong>this is what the <em>async</em> keyword is for</strong>. Apart from allowing await, there’s one more effect of the async keyword:</p><pre>public async Task&lt;T&gt; MyFlow()<br>{<br>    T result = ...//asyncronously produce result of type T<br>    return result;<br>}</pre><p>Note that function return value type is <em>Task&lt;T</em>&gt; but we return an instance of <em>T</em>. Having async in the signature makes compiler to transform the object we return to become the Result of the Task that our function implements.</p><h3><strong>The caveats</strong></h3><p>It would be fair to highlight a few problems that come with async/await usage:</p><ol><li>The call stacks become more convoluted and hard to trace. Arguably, this is not due to having <em>awaits </em>per se, but naturally, the mechanisms implementing asynchrony tend to detach observed consequences (like exceptions) from their root causes. It&#39;s not always feasible to connect them by looking at the call stack.</li><li>An important fact about using <em>await </em>is that it can, and usually does, have associated allocations. These come from two sources:</li></ol><ul><li>Tasks are classes, and therefore creating one allocates memory. Usually, this happens once per lengthy asynchronous workflow that very likely has many other allocations, so it’s not a big deal. But in some cases, a Task describes a process that only rarely takes time and resources but mostly yields a ready result synchronously. Allocating a wrapping Task class may be seen as a burden and could be optimized by using a <a href="https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/"><em>ValueTask</em></a>. This is not a default optimization, though, as it comes with some limitations and hidden pitfalls.</li><li>Remember, in the case of named callback functions, we also needed to introduce member variables to store and pass contexts between callbacks? Then, we could avoid having those variables explicitly by using lambdas, but this leads to the compiler actually allocating memory for capturing needed variables under the hood (this is known as a closure). Since await is effectively a way to rewrite callbacks in a different way, the need for memory to store stuff between parts of the flow persists.</li></ul><p>To clarify it a bit further, <strong>using await per se does not allocate, but the creation of a new Task and the implementation that the compiler generates in place of an async function — usually does.</strong></p><h3><strong>What’s next</strong></h3><p>Here are couple of documentation entry points for anyone wanting to dig deeper.</p><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model">https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model</a></p><p><a href="https://devblogs.microsoft.com/dotnet/how-async-await-really-works/">https://devblogs.microsoft.com/dotnet/how-async-await-really-works/</a></p><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#1515-async-functions">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#1515-async-functions</a></p><p>I’m working on a follow up article that would discuss some practical aspects of using async/await, here are some upcoming topics with few useful links on them</p><ul><li>Practices of<a href="https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library"> handling exceptions in async routines</a></li><li>Providing <a href="https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation">means to cancel an async routine</a></li><li>Ability to have<a href="https://devblogs.microsoft.com/pfxteam/await-anything/"> our own awaitables</a> and describe the custom ways different things could be ‘awaited’</li><li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource-1">Adapting callback-based APIs</a> for use with async/await</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9e632fb0398" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>