<?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 Muhammad Umair on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Umair on Medium]]></description>
        <link>https://medium.com/@mhd.umair?source=rss-524f9867e33c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LrW3qj8fnKz16doPjB1yeg.jpeg</url>
            <title>Stories by Muhammad Umair on Medium</title>
            <link>https://medium.com/@mhd.umair?source=rss-524f9867e33c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:07:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mhd.umair/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[C# 15 Union Types: A Cleaner Way to Model “One of These” Values]]></title>
            <link>https://medium.com/@mhd.umair/c-15-union-types-a-cleaner-way-to-model-one-of-these-values-272ecfaf5ff2?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/272ecfaf5ff2</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 16:52:30 GMT</pubDate>
            <atom:updated>2026-06-19T16:52:30.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2KA1wjoknFh18CbC" /><figcaption>Photo by <a href="https://unsplash.com/@c_b_ozaltun?utm_source=medium&amp;utm_medium=referral">Cenk Batuhan Özaltun</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>C# 15 is introducing “<strong>union types”</strong>, for modeling values that can be exactly one of several known types. Now, you do not have to rely on object types, you can declare a union that makes the set of possible values explicit.</p><pre>public record class Cat(string Name);<br>public record class Dog(string Name);<br>public record class Bird(string Name);<br><br>public union Pet(Cat, Dog, Bird);<br><br>//A Pet can now hold a Cat, Dog, or Bird—and only those cases.<br><br>Pet pet = new Dog(&quot;Rex&quot;);<br><br>string name = pet switch<br>{<br>    Dog d =&gt; d.Name,<br>    Cat c =&gt; c.Name,<br>    Bird b =&gt; b.Name<br>};</pre><p>The key benefit is <strong>compiler-enforced exhaustiveness</strong>. That is one confusing term, I know. The meaning is very simple and straight forward. If you later add another case to the union, the compiler can warn you about switch expressions that have not been updated. That makes unions especially useful in production code where missed cases can turn into runtime bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*GPKUmEJAvfrRizO0e3fZEg.png" /></figure><p>Here are some of the ways you can use it in Production *</p><h3>Example 1: Result-Or-Error Returns</h3><p>Many services return either a successful value or an error. Today, teams often model this with exceptions, nullable values, tuples, or custom Result&lt;T&gt; classes. Union types make the contract clearer.</p><pre>public record class OrderDto(Guid Id, string Status);<br>public record class NotFound(string Resource, string Id);<br>public record class ValidationFailed(IReadOnlyList&lt;string&gt; Errors);<br><br>public union GetOrderResult(OrderDto, NotFound, ValidationFailed);<br><br>public async Task&lt;GetOrderResult&gt; GetOrderAsync(Guid orderId)<br>{<br>    var order = await repository.FindAsync(orderId);<br><br>    if (order is null)<br>    {<br>        return new NotFound(&quot;Order&quot;, orderId.ToString());<br>    }<br><br>    if (!order.CanBeViewed)<br>    {<br>        return new ValidationFailed([&quot;Order cannot be viewed by the current user.&quot;]);<br>    }<br><br>    return new OrderDto(order.Id, order.Status);<br>}</pre><p>The caller must now handle each outcome explicitly:</p><pre>GetOrderResult result = await orderService.GetOrderAsync(orderId);<br><br>IResult response = result switch<br>{<br>    OrderDto order =&gt; Results.Ok(order),<br>    NotFound notFound =&gt; Results.NotFound(notFound),<br>    ValidationFailed validation =&gt; Results.BadRequest(validation.Errors)<br>};</pre><p>This is great fit for APIs, application services, and domain operations where failure is expected and should be represented as data.</p><h3>Example 2: Command Dispatch</h3><p>Union types are also useful when a system processes a known set of commands or messages.</p><pre>public record class CreateCustomer(string Name, string Email);<br>public record class UpdateCustomerEmail(Guid CustomerId, string Email);<br>public record class DeactivateCustomer(Guid CustomerId);<br><br>public union CustomerCommand(<br>    CreateCustomer,<br>    UpdateCustomerEmail,<br>    DeactivateCustomer<br>);</pre><p>A handler can switch over the command:</p><pre>public Task HandleAsync(CustomerCommand command)<br>{<br>    return command switch<br>    {<br>        CreateCustomer create =&gt;<br>            CreateCustomerAsync(create.Name, create.Email),<br><br>        UpdateCustomerEmail update =&gt;<br>            UpdateEmailAsync(update.CustomerId, update.Email),<br><br>        DeactivateCustomer deactivate =&gt;<br>            DeactivateAsync(deactivate.CustomerId)<br>    };<br>}</pre><p>This avoids a loosely typed dispatcher and gives the compiler visibility into the complete command set. When a new command is added, the handler can be updated intentionally instead of silently ignoring the new case.</p><h3>Example 3: Domain States</h3><p>Unions are a good way to model domain concepts where a value can be in one of several valid states.</p><pre>public record class PendingPayment(decimal Amount);<br>public record class Paid(DateTimeOffset PaidAt, string TransactionId);<br>public record class FailedPayment(string Reason);<br>public record class Refunded(DateTimeOffset RefundedAt, decimal Amount);<br><br>public union PaymentState(<br>    PendingPayment,<br>    Paid,<br>    FailedPayment,<br>    Refunded<br>);</pre><p>Then business logic can be written directly against the possible states:</p><pre>public static bool CanShipOrder(PaymentState paymentState)<br>{<br>    return paymentState switch<br>    {<br>        Paid =&gt; true,<br>        PendingPayment =&gt; false,<br>        FailedPayment =&gt; false,<br>        Refunded =&gt; false<br>    };<br>}</pre><p>This is more expressive than strings, enums with extra nullable fields, or base classes used only for pattern matching.</p><h3>When to Use Union Types</h3><p>Union types are most useful when:</p><p>A method returns one of several known outcomes.<br>A workflow has a fixed set of states.<br>A dispatcher handles a closed set of messages or commands.<br>You currently use marker interfaces or base classes mainly to enable pattern matching.<br>You want compile-time warnings when a new case is added but not handled.</p><p>They are probably not the right fit when the set of types is open-ended, plugin-based, or expected to be extended by external assemblies.</p><h3>* Caution: Preview Status</h3><p>Union types are currently part of the C# 15 preview. That means the feature is promising, but teams should be careful about adopting it broadly in production until the language and runtime support are finalized.</p><h3>Learn More</h3><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-15#union-types">Union Types</a></p><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/union">Language Reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=272ecfaf5ff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should I Be Afraid of Agentic Coding?]]></title>
            <link>https://medium.com/@mhd.umair/should-i-be-afraid-of-agentic-coding-a7f9b2600503?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7f9b2600503</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agentic-coding]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 05:18:46 GMT</pubDate>
            <atom:updated>2025-11-22T05:18:46.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s_9sWHN4RCnNytP8" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is a lot of buzz in the dev community about <em>agentic coding</em> — AI tools that don’t just autocomplete code but actually plan, modify and execute features across your codebase.</p><p>Today, I tried Cursor, one of many agentic coding tools, to help implement an AI based feature in one of the core products of my company. The app is built around Windows Forms based tech stack— a tech stack that’s definitely not “AI-optimized.” Here is my prompt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*C5tg-Y7f7xdsJHs63EoNCw.png" /><figcaption>Cursor Prompt. Names changed for privacy</figcaption></figure><p>I was shocked and amazed by how well Cursor executed and delivered the feature, even with very limited knowledge of my application.</p><p>That experience changed my entire perspective on whether agentic coding is something to fear.</p><h3>Why I Expected Cursor to Struggle</h3><p>Win Forms is not exactly the modern, AI-friendly framework you see now adays.</p><ul><li>Much of the UI sits inside designer-generated code</li><li>Event-based logic is scattered across partial classes</li><li>Naming conventions can be inconsistent on older projects</li><li>The tool has no long-term memory of why past architectural decisions were made</li></ul><p>So, I assumed Cursor would hit walls, I would be fixing endless compiler errors, or I would be spending more time <em>correcting</em> the AI than letting it help. Instead, it jumped right in.</p><h3>And Yet — Cursor Just Got It</h3><p>Despite having only, a limited knowledge of my solution, Cursor:</p><ul><li>Understood the structure of my WinForms project</li><li>Located the correct forms and event handlers</li><li>Proposed changes across multiple files</li><li>Generated code that was consistent with the existing architecture</li><li>Asked for confirmation before making any changes</li></ul><p>It behaved like a team member who had skimmed the code for a few minutes, understood the intent, and immediately started contributing.</p><p>The beauty was, the output worked. With <strong>No </strong>correction. That level of productivity from such limited initial knowledge genuinely shocked me.</p><h3>So, Should We Be Afraid of Agentic Coding?</h3><p>No, but we should respect and embrace it.</p><p>Agentic coding tools are powerful. But that doesn’t make them dangerous — it just means they require the same oversight and engineering discipline as any team member.</p><h3>Conclusion: Agentic Coding Doesn’t Remove Developers — It Empowers Them</h3><p>Agentic coding is not the future of development — it’s the present.<br> And instead of threatening our roles, it removes friction from them.</p><p>These tools amplify your abilities — they don’t diminish your value. They are the next step in software engineer evolution.</p><p>More power to you!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7f9b2600503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering: How to Talk to AI Like a Pro]]></title>
            <link>https://medium.com/@mhd.umair/prompt-engineering-how-to-talk-to-ai-like-a-pro-e09b20039c49?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e09b20039c49</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 17:03:01 GMT</pubDate>
            <atom:updated>2025-11-10T17:03:01.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jBsfWYKO8q9Kr69X" /><figcaption>Photo by <a href="https://unsplash.com/@omilaev?utm_source=medium&amp;utm_medium=referral">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AI is changing how we build and manage software. The key skill now? Prompt engineering — crafting clear instructions that make AI tools like Chat GPT (OpenAI), Gemini (Google), Claude (Anthropic), or Llama (Meta) deliver accurate, consistent results.</p><h3>What is prompt engineering</h3><p>Prompt engineering is way for you to interact with a Large Language Model (LLM) to get the best out of it according to your needs. A very basic example:</p><pre>summarize this document ❌</pre><p>A very generic prompt is shown above where LLM assumes a lot of things while answering the question. This may or may not fit your requirement or need.</p><pre>Summarize this document in bullet points highlighting risks, assumptions, <br>and open questions. ✅</pre><p>The prompt above is guiding the AI on how to summarize the document and what you expect from it. This way AI will answer the questions tailored around your need.</p><h3>Base prompt template</h3><p>You can use following universal template to interact with most of the LLMs. You define a persona or a role, explain the objective, give the context, tell it how to format and style, and constraint the output. Not all part of the template is required. You can skip some based on your needs. But the more the merrier.</p><pre>[ROLE] – Define who the AI is (expert persona)<br>[TASK] – What you want done<br>[CONTEXT] – Relevant details or data<br>[FORMAT] – How to structure the output<br>[CONSTRAINTS] – Tone, style, or rules</pre><p>Here is a template you can use</p><pre>You are a [role or expert].  <br>Your task is to [objective].  <br>Context: [relevant info or data].  <br>Format: [bullet points, JSON, markdown, etc.].  <br>Style: [concise, formal, friendly].  <br>If unsure, say “Not enough data” instead of guessing.</pre><h3>LLM Specific Templates</h3><h4>GPT (OpenAI)</h4><pre>You are a [role].  <br>Your task is to [task].  <br>Follow this process step-by-step:<br>1. Analyze the input<br>2. Reason through it<br>3. Produce the final answer<br>Output format: [specify]</pre><blockquote><em>Tip:</em> Use “Let’s reason step-by-step” for better logic and structure.</blockquote><h4>Gemini (Google)</h4><pre>You are a [role].  <br>Given this context: [details], analyze and summarize [task].  <br>Keep it concise and visual if possible.  <br>Format: [bullet points / table / short summary].</pre><blockquote><em>Tip:</em> Put context first — Gemini weighs early text heavily.</blockquote><h4>Claude (Anthropic)</h4><pre>Human: You are a [role]. Your goal is to [task].  <br>Consider the following details carefully: [context].  <br>Please provide a thoughtful, well-structured response in [format].  <br>Assistant:</pre><blockquote><em>Tip:</em> Use natural tone; Claude prefers conversational phrasing.</blockquote><h4>Llama (Meta)</h4><pre>System: You are a helpful [role].  <br>User: [task with clear input].  <br>Output must follow this schema:<br>{<br>  &quot;summary&quot;: &quot;&quot;,<br>  &quot;recommendations&quot;: []<br>}</pre><blockquote>Tip: Keep it compact; Llama performs best with short, strict instructions.</blockquote><p>You can start exploring the realm of LLM prompt engineering by using the templates above. They are merely a starting point for you get into the world of AI. As you learn more your prompts will start to take advantage of AI based on your specific needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e09b20039c49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running DeepSeek-R1 Locally (windows): A Step-by-Step Guide]]></title>
            <link>https://medium.com/@mhd.umair/running-deepseek-r1-locally-windows-a-step-by-step-guide-4aab12e70ba6?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aab12e70ba6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 23:27:22 GMT</pubDate>
            <atom:updated>2025-02-03T23:27:22.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-veHgZycA0UueVso" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artificial Intelligence (AI) is advancing at an incredible pace, and models like <a href="https://www.deepseek.com/"><strong>DeepSeek</strong></a><strong>-R1</strong> are leading the charge in logical reasoning and problem-solving. It is also causing giants to run for their money. Whether you’re a developer, researcher, or AI enthusiast, running <strong>DeepSeek-R1</strong> locally gives you full control over data privacy and performance optimization.</p><p>In this guide, we’ll cover:</p><ul><li>What <strong>DeepSeek-R1</strong> is and why it’s useful</li><li>How to install and run it locally on windows</li></ul><h3>What is DeepSeek-R1?</h3><p>DeepSeek-R1 is an <strong>open-source AI model optimized for logical reasoning and problem-solving.</strong> It can analyze, generate, and debug code, solve mathematical problems, and assist in research tasks. Unlike cloud-based models, <strong>running DeepSeek-R1 locally</strong> ensures <strong>data privacy, lower latency, and offline functionality</strong>.</p><h3>Use Cases of DeepSeek-R1</h3><ol><li><strong>Code Generation &amp; Debugging:</strong> Write and fix Python, JavaScript, and other code snippets.</li><li><strong>Mathematical Problem Solving:</strong> Solve complex equations and explain steps in detail.</li><li><strong>Research Assistance:</strong> Summarize papers, analyze trends, and generate insights.</li><li><strong>Business Analytics:</strong> Interpret market data, predict trends, and provide insights.</li><li><strong>Education &amp; Tutoring:</strong> Explain difficult concepts in various subjects.</li></ol><p>Now, let’s dive into the step-by-step process of running <strong>DeepSeek-R1 locally on windows</strong>.</p><h3>Step-by-Step Guide to Running DeepSeek-R1 Locally</h3><p>To set up and run DeepSeek-R1 on your local machine, follow these simple steps.</p><h3>Step 1: Install Ollama</h3><p>DeepSeek-R1 runs smoothly using <strong>Ollama</strong>, a lightweight tool for running AI models locally. <a href="https://ollama.com/">Download</a> the .exe installer and follow the instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*XbHavE12UCGneaq7ztOCxg.png" /><figcaption>Ollama download page</figcaption></figure><p>Once installed, verify the installation:</p><pre>ollama</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*UgDeA1pCaf1OEhhfhQYF1w.png" /></figure><h3>Step 2: Download DeepSeek-R1</h3><p>Once Ollama is installed, download DeepSeek-R1 by running:</p><pre>ollama run deepseek-r1</pre><p>After some processing its ready to be used</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*YOGj_1RfEWZc5RepAcwq_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*iIC_zHh_7Rj2WJPjuI9oXQ.png" /></figure><p>In the Send a message prompt, start writing your prompts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*V42V3QBcqTaY1wvSjSueVw.png" /></figure><p>You may try other prompts as well to test the capabilities of the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqMWKQOgxqOpNKuSpuCjkQ.png" /></figure><h3>Why Run DeepSeek-R1 Locally?</h3><p>Running AI models locally has several advantages:</p><p>✔ <strong>Privacy &amp; Security:</strong> No cloud data leaks.<br>✔ <strong>Low Latency:</strong> Instant responses without server delays.<br>✔ <strong>Offline Availability:</strong> Works without an internet connection.<br>✔ <strong>Customization:</strong> Fine-tune models to fit your specific needs.</p><h3>Final Thoughts</h3><p>DeepSeek-R1 is an excellent AI model for <strong>reasoning, coding, math, and business applications</strong>. Running it locally ensures <strong>better privacy, control, and performance</strong>. With <strong>Ollama</strong>, setting up and using DeepSeek-R1 is <strong>quick and easy</strong>.</p><p>Whether you’re a developer, student, or AI enthusiast, DeepSeek-R1 can <strong>supercharge your workflow</strong>. Try it out today and explore its potential!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aab12e70ba6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fail Fast Principle]]></title>
            <link>https://medium.com/@mhd.umair/fail-fast-principle-8926babba395?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8926babba395</guid>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[new-product-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 04:32:32 GMT</pubDate>
            <atom:updated>2024-12-02T04:32:32.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0nzb7BktOW4v-siQ" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my current role, my mentor often use word fail fast. At first, I couldn’t understand the reason why failure is acceptable and wondered how failing can lead to success. As time progressed, I realized that this approach towards embracing your failure earlier and actually adapting to the feedback and learning from your failure has tremendous potential to be successful.</p><p>“Fail fast”, in new product initiatives, is a principle that emphasizes rapid experimentation and learning from failures to optimize success. The goal is to quickly test ideas, identify flaws, and make course correction or abandon unworkable concepts before investing a lot of time or money, or resources.</p><h3>Key Aspects of the “Fail Fast” Approach:</h3><ol><li><strong>Rapid Prototyping</strong>: Quickly create a minimum viable product (MVP) to test the concept with real customers.</li><li><strong>Customers’ Feedback</strong>: Gather early and frequent feedback to validate assumptions and refine the product.</li><li><strong>Low Investment</strong>: Use minimal resources to test ideas, reducing the cost of failure.</li><li><strong>Iterative Learning</strong>: Learn from failures, iterate, and improve the product based on insights.</li><li><strong>Early Detection</strong>: Identify flaws or non-viable ideas early in the process to minimize wasted effort.</li></ol><h3>Why It Matters in New Product Initiatives:</h3><ul><li><strong>Reduces Risk</strong>: Avoids large-scale failures by identifying issues early.</li><li><strong>Speeds Up Innovation</strong>: Accelerates the cycle of learning, adapting, and improving.</li><li><strong>Focuses Resources</strong>: Allocates time and money to ideas with the highest potential.</li><li><strong>Encourages Experimentation</strong>: Creates a culture where calculated risks and learning from mistakes are encouraged.</li></ul><h3>Example:</h3><p>A team developing a mobile application may:</p><ol><li>Launch a basic MVP to test core features.</li><li>Collect user feedback and monitor engagement metrices.</li><li>Identify that a key feature is not resonating and pivot to address user needs.</li><li>Iterate based on findings, improving the app without heavy upfront costs.</li></ol><p>In essence, the “fail fast” approach embraces failure as a learning opportunity, enabling teams to refine their vision and deliver successful products more efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8926babba395" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RFC 9457: Problem Details for HTTP APIs]]></title>
            <link>https://medium.com/@mhd.umair/understanding-rfc-9457-problem-details-for-http-apis-6bdb675e685f?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bdb675e685f</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 01:01:50 GMT</pubDate>
            <atom:updated>2024-11-15T01:01:50.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Ef_BxRQGNtc4Mt_" /><figcaption>Photo by <a href="https://unsplash.com/@woodies11?utm_source=medium&amp;utm_medium=referral">Romson Preechawit</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p><a href="https://www.rfc-editor.org/rfc/rfc9457.html">RFC 9457</a> define a standard way to communicate errors in HTTP APIs by offering a consistent problem details format. This standardized error structure makes it easier for clients to interpret and handle issues, providing fields such as “type,” “title,” “status,” “detail,” and “instance” to give users valuable context. This structure is specially helpful for debugging in distributed systems and when integratting different APIs.</p><p><strong>Key Fields in RFC 9457</strong></p><ul><li><strong>type</strong>: URI reference identifying the problem type.</li><li><strong>title</strong>: Short, human-readable summary of the issue.</li><li><strong>status</strong>: HTTP status code representing the error.</li><li><strong>detail</strong>: Detailed description of the issue.</li><li><strong>instance</strong>: URI reference pointing to the specific occurrence of the problem.</li></ul><p><strong>Implementing RFC 9457 in .NET Core</strong></p><p>In .NET Core, you can implement RFC 9457 by creating a ProblemDetails class and returning it in API error responses. Here’s how to set up the RFC 9457-compliant error handling with examples.</p><p><strong>Example: Using </strong><strong>ProblemDetails in .NET Core</strong></p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    app.UseExceptionHandler(config =&gt;<br>    {<br>        config.Run(async context =&gt;<br>        {<br>            context.Response.StatusCode = StatusCodes.Status400BadRequest;<br>            context.Response.ContentType = &quot;application/problem+json&quot;;<br><br>            var problemDetails = new ProblemDetails<br>            {<br>                Type = &quot;https://example.com/probs/out-of-stock&quot;,<br>                Title = &quot;Item Out of Stock&quot;,<br>                Status = StatusCodes.Status400BadRequest,<br>                Detail = &quot;The item you requested is out of stock.&quot;,<br>                Instance = context.Request.Path<br>            };<br><br>            await context.Response.WriteAsJsonAsync(problemDetails);<br>        });<br>    });<br>}</pre><p><strong>Customizing Problem Details</strong></p><p>You can extend ProblemDetails to include more fields for specific error cases.</p><pre>[HttpGet(&quot;items/{id}&quot;)]<br>public IActionResult GetItem(int id)<br>{<br>    if (item == null)<br>    {<br>        return NotFound(new CustomProblemDetails<br>        {<br>            Type = &quot;https://example.com/probs/not-found&quot;,<br>            Title = &quot;Item Not Found&quot;,<br>            Status = StatusCodes.Status404NotFound,<br>            Detail = $&quot;Item with id {id} was not found.&quot;,<br>            AdditionalInfo = &quot;Check the inventory list for available items.&quot;<br>        });<br>    }<br><br>    return Ok(item);<br>}</pre><p><strong>Conclusion</strong></p><p>Using RFC 9457 in .NET Core simplified error handling, providing clients with clear, consistent, and actionable information on issues. The ProblemDetails approach also improves API maintainability and debugging. Integrating it into your application can enhance the user experience and make your APIs easier to use and integrate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bdb675e685f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power Automate — More power to you]]></title>
            <link>https://medium.com/@mhd.umair/power-automate-more-power-to-you-ed034a68436d?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed034a68436d</guid>
            <category><![CDATA[power-automate]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[microsoft-flow]]></category>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[automation-software]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 00:07:01 GMT</pubDate>
            <atom:updated>2024-10-25T00:07:01.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Power Automate — More power to you</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g1rX6av1-huhgn1v" /><figcaption>Photo by <a href="https://unsplash.com/@jakubzerdzicki?utm_source=medium&amp;utm_medium=referral">Jakub Żerdzicki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s fast paced business environment, automation plays a crucial role in increasing efficiency and reducing manual workloads. <a href="https://make.powerautomate.com/"><strong>Microsoft Power Automate</strong></a> (formerly known as Microsoft Flow) is a cloud-based service that allows users to automate repetitive tasks and workflows across various applications and services. With its intuitive design, Power Automate enables both non-technical users and developers to create automated workflows quickly, streamlining complex business processes without the needs for extensive coding.</p><p>Power Automate is a low-code solution which enables businesses to create “flows” — automated workflows that can be triggered by a variety of events and perform actions across different services and third-party applications.</p><h3>Key Features of Power Automate</h3><ul><li><strong>Automated Flows</strong>: Triggered by the events like receiving emails.</li><li><strong>Instant Flows</strong>: Manually triggered via a button.</li><li><strong>Scheduled Flows</strong>: Run at a predefined times.</li><li><strong>UI Flows</strong>: Automate tasks using Robotic Process Automation (RPA).</li></ul><h3>Solving a Common Problem: Employee Onboarding Automation</h3><p>Employee onboarding is often a time-consuming and error-prone process involving HR, IT, and Facilities. Power Automate can streamline this by automating the following:</p><ol><li><strong>Document Collection</strong>: Sends automated requests and reminders for new hire documents.</li><li><strong>Account Setup</strong>: Integrates with Active Directory to automatically create user accounts.</li><li><strong>Equipment Provisioning</strong>: Triggers equipment requests for the Facilities team.</li><li><strong>Policy Acknowledgments</strong>: Sends policy documents for new hires to review and tracks acknowledgments.</li><li><strong>Reporting</strong>: Tracks onboarding progress and generates reports for HR and managers.</li></ol><h3>Benefits of Using Power Automate</h3><ul><li><strong>Increased Efficiency</strong>: Automates repetitive tasks, freeing up HR and IT.</li><li><strong>Reduced Errors</strong>: Minimizes manual mistakes in key processes.</li><li><strong>Faster Onboarding</strong>: Ensures timely completion of all steps.</li><li><strong>Scalability</strong>: Handles onboarding at any scale with ease.</li></ul><p>Power Automate is an ideal solution for enterprises looking to automate complex workflows, boost productivity, and improve operational efficiency.</p><p>Power Automate come with pre-built templates to perform common tasks. You can start your flow with these templates which will do the initial setup for you to consume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljumyi3DlkgM9oJBDojFeA.png" /><figcaption>Screen shot of templates offered by Power Automate</figcaption></figure><p>Power Automate also has great <a href="https://make.powerautomate.com/documentation">documentation </a>and an amazing <a href="https://community.powerplatform.com/">community support</a>. If you are working on a flow, there is a high probability that someone in the community has already come across similar workflow.</p><h3>Further reading</h3><p><a href="https://learn.microsoft.com/en-us/training/modules/get-started-with-form-processing/">Process custom documents with AI Builder</a></p><p><a href="https://learn.microsoft.com/en-us/training/browse/?products=ai-builder%2Cpower-automate">Use AI in your flows</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed034a68436d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s New in C# 13: Key Features with Examples]]></title>
            <link>https://medium.com/@mhd.umair/whats-new-in-c-13-key-features-with-examples-5db94604cf88?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5db94604cf88</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 02:37:41 GMT</pubDate>
            <atom:updated>2024-10-18T02:37:41.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xHHOtL59SAY8R5uQ" /><figcaption>Photo by <a href="https://unsplash.com/@vingtcent?utm_source=medium&amp;utm_medium=referral">Vincent Guth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>C# 13 introduces new enhancements that make the language mre powerful and flexible. These updates are aligned with the .NET 9 preview, and developers can try them with Visual Studio 2022. Below is a blog post covering some of the most exciting new features in C# 13, with examples to demonstrate how to use them effectively.</p><h3>1. params Collections</h3><p>Previously, the params modifier was limited to arrays, but in C# 13, you can use it with any collection type like IEnumerable&lt;T&gt;, Span&lt;T&gt;, or ReadOnlySpan&lt;T&gt;. This flexibility simplifies handling varying numbers of arguments for collection types.</p><h4>Example:</h4><pre>public void Concat&lt;T&gt;(params ReadOnlySpan&lt;T&gt; items)<br>{<br>    foreach (var item in items)<br>    {<br>        Console.Write($&quot;{item} &quot;);<br>    }<br>    Console.WriteLine();<br>}<br><br>ReadOnlySpan&lt;int&gt; numbers = stackalloc int[] { 1, 2, 3 };<br>Concat(numbers);</pre><h3>2. New Lock Type</h3><p>C# 13 introduces a new lock type System.Threading.Lock, which provides better thread synchronization than the traditional Monitor-based locks.</p><p>This lock mechanism offers more efficient thread synchronization by using the Dispose() pattern to release the lock.</p><h3>3. New Escape Sequence \e</h3><p>C# 13 adds support for a new escape sequence \e representing the ESCAPE character (U+001B). This simplifies using escape sequences in strings, making the code more readable than using \x1b or \u001b.</p><h3>4. Implicit Indexer Access in Object Initializers</h3><p>You can now use the “from the end” operator (^) in object initializers to assign values starting from the last element.</p><p>This enables a more intuitive way to access elements from the end when initializing arrays or collections.</p><h3>5. Method Group Natural Type Improvements</h3><p>C# 13 optimizes overload resolution for method groups by pruning the set of candidate methods earlier, improving performance. This makes the compiler behave more predictably and efficiently when determining the method signature to use.</p><h3>Conclusion</h3><p>I have not tried all of the features C# 13 has to offer. I would love to see how these features can be incorporated in code to enhance the code. Remember one thing, these are preview features which may change when the actual C# 13 is released. Be sure to explore these features with the latest .NET 9 preview to enhance your development workflow.</p><p>Further reading:</p><p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13#new-lock-object">C# 13</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5db94604cf88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding CancellationToken in .NET Core]]></title>
            <link>https://medium.com/@mhd.umair/understanding-cancellationtoken-in-net-core-0221c7f715a1?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0221c7f715a1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 03:11:30 GMT</pubDate>
            <atom:updated>2024-10-08T03:11:30.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding CancellationToken in .NET Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OrEw2frEGot_jRCC" /><figcaption>Photo by <a href="https://unsplash.com/@erwanhesry?utm_source=medium&amp;utm_medium=referral">Erwan Hesry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In modern applications, especially those that involve asynchronous programming, it is crucial to have a mechanism to cancel operations gracefully. The CancellationToken structure in .NET Core provides a way to communicate cancellation requests to asynchronous methods. In this blog post, we will explore the flow of using CancellationToken, how it is injected, and provide an example to illustrate its usage.</p><h4>What is CancellationToken?</h4><p>CancellationToken is part of the System.Threading namespace and is used to signal that an operation should be canceled. It works alongside CancellationTokenSource, which is responsible for creating tokens and issuing cancellation requests.</p><p>The primary components are:</p><ol><li><strong>CancellationTokenSource</strong>: A class that provides a way to signal cancellation.</li><li><strong>CancellationToken</strong>: A struct that represents the cancellation request and can be passed to methods that support cancellation.</li></ol><h4>Flow of CancellationToken</h4><ol><li><strong>Create a </strong><strong>CancellationTokenSource</strong>: This object is responsible for issuing the cancellation request.</li><li><strong>Get the </strong><strong>CancellationToken</strong>: The token from the CancellationTokenSource is obtained and can be passed to methods that might need to be canceled.</li><li><strong>Pass the Token to Asynchronous Methods</strong>: Methods that support cancellation should accept a CancellationToken parameter.</li><li><strong>Check for Cancellation</strong>: Inside the method, regularly check the token’s status to see if cancellation has been requested.</li><li><strong>Trigger Cancellation</strong>: Call the Cancel method on the CancellationTokenSource when you want to cancel the operation.</li></ol><h4>Example: Using CancellationToken</h4><p>Let’s look at a simple example where we create a method that performs a long-running operation (simulated with Task.Delay) and supports cancellation.</p><pre>using System;<br>using System.Threading;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        // Create a CancellationTokenSource<br>        using var cts = new CancellationTokenSource();<br><br>        // Start the long-running task and pass the token<br>        var longRunningTask = LongRunningOperation(cts.Token);<br><br>        // Simulate waiting for a while before cancellation<br>        await Task.Delay(2000);<br>        <br>        // Request cancellation<br>        cts.Cancel();<br>        Console.WriteLine(&quot;Cancellation requested.&quot;);<br><br>        try<br>        {<br>            // Await the long-running task<br>            await longRunningTask;<br>        }<br>        catch (OperationCanceledException)<br>        {<br>            Console.WriteLine(&quot;Operation was canceled.&quot;);<br>        }<br>    }<br><br>    static async Task LongRunningOperation(CancellationToken cancellationToken)<br>    {<br>        for (int i = 0; i &lt; 5; i++)<br>        {<br>            // Check if cancellation has been requested<br>            cancellationToken.ThrowIfCancellationRequested();<br><br>            Console.WriteLine($&quot;Running operation {i + 1}...&quot;);<br>            await Task.Delay(1000); // Simulate work<br>        }<br>        Console.WriteLine(&quot;Operation completed successfully.&quot;);<br>    }<br>}</pre><p>Output</p><pre>Running operation 1...<br>Running operation 2...<br>Running operation 3...<br>Cancellation requested.<br>Operation was canceled.</pre><h3>Explanation of the Example</h3><ol><li><strong>Creating a </strong><strong>CancellationTokenSource</strong>: In the Main method, we create an instance of CancellationTokenSource which will be used to signal cancellation.</li><li><strong>Starting the Long-Running Task</strong>: The LongRunningOperation method is called with the CancellationToken from the source. This method simulates a long-running task by iterating and pausing for a second each time.</li><li><strong>Simulating Delay and Cancellation</strong>: We simulate a delay in the Main method, during which the task is running. After 2 seconds, we request cancellation by calling cts.Cancel().</li><li><strong>Handling Cancellation</strong>: Inside LongRunningOperation, we check if cancellation has been requested using cancellationToken.ThrowIfCancellationRequested(). If cancellation is requested, an OperationCanceledException is thrown, which we catch in the Main method to handle the cancellation gracefully.</li></ol><h3>Conclusion</h3><p>Using CancellationToken is a powerful way to handle cancellation in .NET Core applications. It allows for responsive and resource-efficient applications by letting tasks respond to cancellation requests. Implementing cancellation in your asynchronous methods not only improves the user experience but also optimizes resource management in your applications.</p><p>With this understanding, you can start incorporating CancellationToken into your own projects, allowing for better control over long-running tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0221c7f715a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Task.WaitAll and Task.WhenAll in C#]]></title>
            <link>https://medium.com/@mhd.umair/understanding-task-waitall-and-task-whenall-in-c-86eebd42d550?source=rss-524f9867e33c------2</link>
            <guid isPermaLink="false">https://medium.com/p/86eebd42d550</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[application-performance]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Muhammad Umair]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 19:42:15 GMT</pubDate>
            <atom:updated>2024-09-21T21:57:07.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AFkvdMszRc2naxw8" /><figcaption>Photo by <a href="https://unsplash.com/@marcojodoin?utm_source=medium&amp;utm_medium=referral">Marc-Olivier Jodoin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In modern software development, asynchronous programming plays a crucial role in enhancing performance by improving the responsiveness and scalability of applications. In C#, two common methods for dealing with multiple asynchronous tasks are <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitall?view=net-8.0">Task.WaitAll</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=net-8.0">Task.WhenAll</a>. While both methods are designed to wait for a group of tasks to complete, they work differently and should be used in specific contexts.</p><p>This blog post will walk through the differences between these methods, showcase examples with output, and provide insights on how they can improve performance.</p><h3>1. Task.WaitAll Overview</h3><p>Task.WaitAll is a blocking call that waits for all the provided taks to complete before proceeding. This method blocks the current thread until all tasks are done.</p><pre>using System;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        Task[] tasks = new Task[]<br>        {<br>            Task.Run(() =&gt; DoWork(1, 2000)),<br>            Task.Run(() =&gt; DoWork(2, 3000)),<br>            Task.Run(() =&gt; DoWork(3, 1000))<br>        };<br><br>        // Blocking call: Waits for all tasks to complete<br>        Task.WaitAll(tasks);<br><br>        Console.WriteLine(&quot;All tasks completed.&quot;);<br>    }<br><br>    static void DoWork(int taskId, int delay)<br>    {<br>        Console.WriteLine($&quot;Task {taskId} started.&quot;);<br>        Task.Delay(delay).Wait();<br>        Console.WriteLine($&quot;Task {taskId} completed.&quot;);<br>    }<br>}</pre><p>Output:</p><pre>Task 1 started.<br>Task 2 started.<br>Task 3 started.<br>Task 3 completed.<br>Task 1 completed.<br>Task 2 completed.<br>All tasks completed.</pre><h4>Explanation:</h4><ul><li>In this example, three tasks are initiated, and the Task.WaitAll(tasks) call blocks the main thread until all tasks complete.</li><li>While all tasks run in parallel, the thread waits for the slowest one to finish, reducing the responsiveness of the main thread.</li></ul><h3>2. Task.WhenAll Overview</h3><p>Unlike Task.WaitAll, Task.WhenAll is an asynchronous method that allows the current thread to continue executing while awaiting the completion of the tasks. This is crucial for scenarios where we need to avoid blocking the main thread.</p><pre>using System;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        Task[] tasks = new Task[]<br>        {<br>            Task.Run(() =&gt; DoWork(1, 2000)),<br>            Task.Run(() =&gt; DoWork(2, 3000)),<br>            Task.Run(() =&gt; DoWork(3, 1000))<br>        };<br><br>        // Non-blocking call: Waits for all tasks asynchronously<br>        await Task.WhenAll(tasks);<br><br>        Console.WriteLine(&quot;All tasks completed asynchronously.&quot;);<br>    }<br><br>    static async Task DoWork(int taskId, int delay)<br>    {<br>        Console.WriteLine($&quot;Task {taskId} started.&quot;);<br>        await Task.Delay(delay);<br>        Console.WriteLine($&quot;Task {taskId} completed.&quot;);<br>    }<br>}</pre><p>Output</p><pre>Task 1 started.<br>Task 2 started.<br>Task 3 started.<br>Task 3 completed.<br>Task 1 completed.<br>Task 2 completed.<br>All tasks completed asynchronously.</pre><h4>Explanation:</h4><ul><li>Here, Task.WhenAll(tasks) is awaited asynchronously, allowing the main thread to continue without being blocked.</li><li>This is particularly useful in UI or web applications where maintaining responsiveness is critical.</li></ul><h3>3. Performance Improvement: Choosing the Right Method</h3><p>When it comes to improving performance, selecting between Task.WaitAll and Task.WhenAll depends on the specific scenario:</p><h4>Use Task.WaitAll when:</h4><ul><li>You are in a console or background application and blocking the main thread is acceptable.</li><li>You don’t need to handle the tasks asynchronously or make the application responsive.</li></ul><h4>Use Task.WhenAll when:</h4><ul><li>You are in a UI application or a web service where you must avoid blocking the main thread.</li><li>You want to leverage the benefits of asynchronous programming, allowing other tasks to execute while awaiting the results of the ongoing tasks.</li></ul><h3>4. Example of Improved Performance Using Task.WhenAll</h3><p>uppose you are building a web API that fetches data from multiple external services. If each request is sent sequentially, the total time would be the sum of all response times. By using Task.WhenAll, you can make these calls in parallel, significantly improving the performance of your API.</p><p>Synchronous aka Sequential Code</p><pre>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        var result1 = await GetDataFromService1();<br>        var result2 = await GetDataFromService2();<br><br>        Console.WriteLine(&quot;All data fetched.&quot;);<br>    }<br><br>    static async Task&lt;string&gt; GetDataFromService1()<br>    {<br>        using (HttpClient client = new HttpClient())<br>        {<br>            var result = await client.GetStringAsync(&quot;https://example.com/service1&quot;);<br>            return result;<br>        }<br>    }<br><br>    static async Task&lt;string&gt; GetDataFromService2()<br>    {<br>        using (HttpClient client = new HttpClient())<br>        {<br>            var result = await client.GetStringAsync(&quot;https://example.com/service2&quot;);<br>            return result;<br>        }<br>    }<br>}</pre><p>In this sequential case, the total time will be the sum of both service response times.</p><p>Improved Performance with Task.WhenAll</p><pre>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        Task&lt;string&gt; task1 = GetDataFromService1();<br>        Task&lt;string&gt; task2 = GetDataFromService2();<br><br>        await Task.WhenAll(task1, task2);<br><br>        Console.WriteLine(&quot;All data fetched in parallel.&quot;);<br>    }<br><br>    static async Task&lt;string&gt; GetDataFromService1()<br>    {<br>        using (HttpClient client = new HttpClient())<br>        {<br>            var result = await client.GetStringAsync(&quot;https://example.com/service1&quot;);<br>            return result;<br>        }<br>    }<br><br>    static async Task&lt;string&gt; GetDataFromService2()<br>    {<br>        using (HttpClient client = new HttpClient())<br>        {<br>            var result = await client.GetStringAsync(&quot;https://example.com/service2&quot;);<br>            return result;<br>        }<br>    }<br>}</pre><p>In this case, both service calls are initiated in parallel, reducing the total time to the duration of the slower service rather than the sum of both.</p><h3>Conclusion</h3><p>Both Task.WaitAll and Task.WhenAll serve useful purposes, but they should be used in different contexts:</p><ul><li><strong>Task.WaitAll</strong> is ideal for synchronous scenarios where blocking is acceptable.</li><li><strong>Task.WhenAll</strong> excels in asynchronous contexts, allowing for better responsiveness and performance.</li></ul><p>By understanding these methods, you can design efficient and performant applications in C# that make the most of modern asynchronous programming practices.</p><p>Further reading:</p><p><a href="https://thesharperdev.com/csharps-whenall-and-exception-handling/">C#’s WhenAll and Exception Handling | TheSharperDev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86eebd42d550" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>