<?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 Sandra Ibrahim Sadik on Medium]]></title>
        <description><![CDATA[Stories by Sandra Ibrahim Sadik on Medium]]></description>
        <link>https://medium.com/@sandra.ibrahim00?source=rss-70b1359fad8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ip4ATEr1YbTea_wcRTlv2Q.jpeg</url>
            <title>Stories by Sandra Ibrahim Sadik on Medium</title>
            <link>https://medium.com/@sandra.ibrahim00?source=rss-70b1359fad8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:51:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandra.ibrahim00/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[Is Async/Await Killing Your App’s Performance?]]></title>
            <link>https://medium.com/deloitte-uk-cloud-blog/is-async-await-killing-your-apps-performance-6beefe1b3b4b?source=rss-70b1359fad8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6beefe1b3b4b</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Sandra Ibrahim Sadik]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 11:48:20 GMT</pubDate>
            <atom:updated>2026-08-03T11:48:20.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="An image describes a function with async and await words" src="https://cdn-images-1.medium.com/max/1024/0*SNk5jM5CXx-znu0i.png" /><figcaption>An image describes a function with async and await words</figcaption></figure><p>For a long time, I used async and await under the assumption that they were a &#39;magic button&#39; to make my code faster. But as I dug deeper, I realized that isn’t exactly true.</p><p>In Fact async is powerful, but not always the right tool for the job. There are cases where it’s a lifesaver and others where it actually adds unnecessary overhead.</p><p>In this guide, I’ll share what I’ve learned about using async and await effectively in .NET, along with some best practices.</p><h4><strong>Table of Contents</strong></h4><ul><li><a href="#8dd5">Scenarios</a></li><li><a href="#713e">The Hidden Tax</a></li><li><a href="#7303">Guidance Rules</a></li><li><a href="#7863">The Final Challenge</a></li><li><a href="#2c84">Summary</a></li><li><a href="#21f8">References</a></li></ul><h4><strong>When to Use Async /Await:</strong></h4><ul><li><strong>I/O-Bound Work:</strong> When you need to read files, send network requests, or call databases, await pauses the method without blocking the thread, releasing it to do other work.(Microsoft, 2022)</li><li><strong>For UI Apps (WPF / MAUI):</strong> In my opinion, use Task.Runto offload heavy CPU work to keep the main UI thread from freezing.</li><li><strong>For Web APIs (ASP.NET Core):</strong> I believe that avoiding<strong> </strong>Task.Run in ASP.NET already manages threads efficiently. Forcing triggers unnecessary context switching and causes <strong>Thread Starvation</strong> under high traffic.</li><li><strong>The Exception:</strong> I believe it should only be used in web apps for true “fire-and-forget” background tasks that don’t need to block the HTTP response.</li></ul><h4>The Hidden Tax:</h4><p>Let’s pause for a second and look at what happens under the hood of a simple async and await method. By seeing what’s happening in the background, it becomes much clearer why we should think twice before using them everywhere.</p><p>copy and paste 4 simple lines of code on <a href="https://sharplab.io/"><em>SharpLab.io</em></a></p><pre>using System.Threading.Tasks;<br><br>public class C {<br>    public async Task GetData() {<br>        await Task.Yield(); <br>    }<br>}</pre><p>the decompiled C# output</p><pre>[CompilerGenerated]<br>private sealed class &lt;GetData&gt;d__0 : IAsyncStateMachine<br>{<br>    public int &lt;&gt;1__state;<br>    public AsyncTaskMethodBuilder &lt;&gt;t__builder;<br>    private YieldAwaitable.YieldAwaiter &lt;&gt;u__1;<br><br>    private void MoveNext()<br>    {<br>        int num = &lt;&gt;1__state;<br>        try<br>        {<br>            YieldAwaitable.YieldAwaiter awaiter;<br>            if (num != 0)<br>            {<br>                awaiter = Task.Yield().GetAwaiter();<br>                if (!awaiter.IsCompleted)<br>                {<br>                    num = (&lt;&gt;1__state = 0);<br>                    &lt;&gt;u__1 = awaiter;<br>                    &lt;&gt;t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);<br>                    return;<br>                }<br>            }<br>            else<br>            {<br>                awaiter = &lt;&gt;u__1;<br>                &lt;&gt;u__1 = default(YieldAwaitable.YieldAwaiter);<br>                num = (&lt;&gt;1__state = -1);<br>            }<br>            awaiter.GetResult();<br>        }<br>        catch (Exception exception)<br>        {<br>            &lt;&gt;1__state = -2;<br>            &lt;&gt;t__builder.SetException(exception);<br>            return;<br>        }<br>        &lt;&gt;1__state = -2;<br>        &lt;&gt;t__builder.SetResult();<br>    }<br>    // ... (rest of the interface implementation)<br>}</pre><p>My 4-line method has been transformed into a complex sealed class (the <strong>State Machine</strong>). Even in this tiny example, you can see the &#39;hidden tax&#39; of async:</p><ul><li><strong>The Bookmark:</strong> The &lt;&gt;1__state variable is created just to remember where we are.</li><li><strong>The Safety Net:</strong> An entire try/catch block was added to capture exceptions and wrap them into a Task.</li><li><strong>The Builder:</strong> The AsyncTaskMethodBuilder has to be initialized to manage the lifecycle</li></ul><h4>So let’s do it wisely.<strong> These tips are drawn from my experience:</strong></h4><p><strong>1. The “Async All the Way” Rule</strong></p><p>When you use .Result or .Wait(), you are effectively telling the thread to sit and wait for the <strong>State Machine</strong> to finish its work. But here’s the trap: if that state machine needs the same thread to resume its &quot;Bookmark&quot; (the &lt;&gt;1__state), you get a <strong>Deadlock</strong>. The thread is waiting for the task, and the task is waiting for the thread.</p><ul><li><strong>Solution:</strong> Always use await. It allows the thread to be productive elsewhere while the state machine handles the &quot;waiting&quot; in the background.</li></ul><p><strong>2. Avoid </strong><strong>async void (The Silent Crasher)</strong></p><p><strong>Always return a </strong><strong>Task or </strong><strong>Task&lt;T&gt;.</strong> Remember the <strong>Safety Net</strong> (the try/catch block) we saw in the decompiled code? When you return a Task, the state machine has a place to store any errors that happen. It puts the exception inside the Task object for you to handle later.</p><ul><li><strong>The Risk:</strong> With async void, there is no Task object. There is no place for that &quot;Safety Net&quot; to store the error. The exception has nowhere to go but directly to the system, which usually results in your entire application crashing.</li><li><strong>The Exception:</strong> Only use async void for UI Event Handlers (like button clicks) where you have no other choice.</li></ul><pre>public async void AsyncVoidMethodThrowsException()<br>{<br>    throw new Exception(&quot;Hmmm, something went wrong!&quot;);<br>}<br><br>public void ThisWillNotCatchTheException()<br>{<br>    try<br>    {<br>        AsyncVoidMethodThrowsException();<br>    }<br>    catch(Exception ex)<br>    {<br>        //The below line will never be reached<br>        Debug.WriteLine(ex.Message);<br>    }<br>}</pre><p><strong>3. Respect the CancellationToken</strong></p><p>When you start an async task without a token, you’re turning that engine on and walking away. Even if the user cancels their request, that engine—the sealed class, the MoveNext() logic, and the Heap memory—will keep running until it finishes.</p><ul><li><strong>The Goal:</strong> Use tokens to kill the State Machine the moment it’s no longer needed. It saves your CPU and lets the Garbage Collector reclaim that Heap space immediately.</li></ul><p><strong>4. Use </strong><strong>ValueTask Sparingly: Don&#39;t Over-Optimize</strong></p><p>ValueTask&lt;T&gt; is a struct (a value type), not a class. Because it is a struct, it prefers to live on the Stack.</p><p>When you use <strong>ValueTask</strong>, .NET handles it in two different ways depending on how the code runs.</p><ul><li><strong>The Catch:</strong> It only stays on the stack if the method finishes <em>instantly</em> (synchronously). If your method actually has to wait (the asynchronous path), that ValueTask is often moved to the Heap anyway.</li><li><strong>The Rule:</strong> Stick to the standard Task for readability and safety. Only reach for ValueTask if you are writing high-performance code where you’ve proven that Task allocations are your primary bottleneck.</li></ul><blockquote>Please see Okyrylchuk’s write-up for an example and explanation of the topic discussed above:</blockquote><blockquote><a href="https://okyrylchuk.dev/blog/understanding-valuetask-in-csharp/"><em>https://okyrylchuk.dev/blog/understanding-valuetask-in-csharp/</em></a> )</blockquote><h4><strong>You’ve reached the end, so it’s your turn now ;)</strong></h4><pre>var cts = new CancellationTokenSource();<br><br>// We pass the token to Task.Run... so it&#39;s safe, right?<br>var task = Task.Run(() =&gt; <br>{<br>    // Simulating heavy work<br>    for (int i = 0; i &lt; 100; i++)<br>    {<br>        Thread.Sleep(100); <br>        Console.WriteLine($&quot;Working... {i}%&quot;);<br>    }<br>}, cts.Token);<br><br>// Triggering cancellation after 1 second<br>await Task.Delay(1000);<br>cts.Cancel();<br><br>await task;<br>Console.WriteLine(&quot;Task Finished!&quot;);</pre><h4>The Question:</h4><p>Does the loop stop running the moment cts.Cancel() is called?</p><ul><li><strong>A)</strong> Yes, because the token was passed to Task.Run.</li><li><strong>B)</strong> No, the loop will continue to 100% and then the Task will finish.</li><li><strong>C)</strong> Yes, but only after the current Thread.Sleep finishes.</li></ul><h4>The Answer (Don’t scroll down until you’ve guessed!)</h4><p><strong>The answer is B.</strong></p><p><strong>The Explanation:</strong> This is one of the most common mistakes in .NET. Passing cts.Token to Task.Run only tells the <strong>Task Scheduler</strong> not to <em>start</em> the task if it&#39;s already canceled.</p><p>Once the code inside the {} starts running, it is your responsibility to check that token. The .NET runtime will not &quot;kill&quot; your thread or inject an exception into your loop for you.</p><p><strong>fixed version</strong></p><pre>var cts = new CancellationTokenSource();<br>var token = cts.Token;<br><br>var task = Task.Run(() =&gt; <br>{<br>    for (int i = 0; i &lt; 100; i++)<br>    {<br>        // THE FIX: The State Machine now checks the &#39;Stop&#39; signal <br>        // at the start of every iteration.<br>        token.ThrowIfCancellationRequested(); <br><br>        Thread.Sleep(100); <br>        Console.WriteLine($&quot;Working... {i}%&quot;);<br>    }<br>}, token);<br><br>// Triggering cancellation after 1 second<br>await Task.Delay(1000);<br>cts.Cancel();<br><br>try <br>{<br>    await task;<br>}<br>catch (OperationCanceledException)<br>{<br>    Console.WriteLine(&quot;Task was stopped gracefully!&quot;);<br>}<br><br>Console.WriteLine(&quot;Done&quot;);</pre><h4>Summary</h4><p>async and await are powerful tools, but they aren’t free. They come with a &quot;hidden tax&quot;—a state machine that manages your code behind the scenes.</p><p>Use them when your app needs to wait (I/O) or stay responsive (UI), but avoid using them blindly. Remember:</p><ul><li>Always check your CancellationToken.</li><li>Never use async void (unless it&#39;s a UI event).</li><li>Keep your “Async all the way” chain intact to avoid deadlocks.</li></ul><p>Writing better asynchronous code doesn’t just make your app faster — it makes it more reliable.</p><h4><strong>Let’s Swap Stories! 💬</strong></h4><p>Was this breakdown helpful? If you’ve ever been personally victimized by a tricky deadlock or an async void crash, drop a comment below and share your insights!</p><h4><strong>References</strong></h4><p><a href="https://learn.microsoft.com/en-us/shows/on-dotnet/brandon-minnick-asyncawait-best-practices"><em>https://learn.microsoft.com/en-us/shows/on-dotnet/brandon-minnick-asyncawait-best-practices</em></a></p><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/"><em>https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/</em></a></p><p><a href="https://youtu.be/dZaisKHwqFE?si=A-UJtLVU3DiQb5S2"><em>https://youtu.be/dZaisKHwqFE?si=A-UJtLVU3DiQb5S2</em></a></p><p><a href="https://youtu.be/dZaisKHwqFE?si=AnBeMm861ICm3RKA"><em>https://youtu.be/dZaisKHwqFE?si=AnBeMm861ICm3RKA</em></a></p><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/async-scenarios"><em>Asynchronous programming scenarios — C# | Microsoft Learn</em></a></p><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model"><em>The Task Asynchronous Programming (TAP) model with async and await” — C# | Microsoft Learn</em></a></p><p><em>Note: This article reflects only my personal views and experiences and is not published on behalf of Deloitte LLP or associated firms. It does not constitute professional or legal advice.</em></p><p><em>All product names, logos, and brands are the property of their respective owners. All company, product, and service names used on this website are for identification purposes only. Use of these names, logos, and brands does not imply endorsement.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6beefe1b3b4b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deloitte-uk-cloud-blog/is-async-await-killing-your-apps-performance-6beefe1b3b4b">Is Async/Await Killing Your App’s Performance?</a> was originally published in <a href="https://medium.com/deloitte-uk-cloud-blog">Deloitte UK Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>