<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Habib BARAKET</title>
    <description>The latest articles on DEV Community by Habib BARAKET (@habib_baraket).</description>
    <link>https://dev.to/habib_baraket</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3192809%2Ff8acd12b-0864-4a29-b58a-31adcb652b06.png</url>
      <title>DEV Community: Habib BARAKET</title>
      <link>https://dev.to/habib_baraket</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/habib_baraket"/>
    <language>en</language>
    <item>
      <title>.Wait() or .Result on a Task in an async context</title>
      <dc:creator>Habib BARAKET</dc:creator>
      <pubDate>Fri, 23 May 2025 15:57:43 +0000</pubDate>
      <link>https://dev.to/habib_baraket/wait-or-result-on-a-task-in-an-async-context-2bbh</link>
      <guid>https://dev.to/habib_baraket/wait-or-result-on-a-task-in-an-async-context-2bbh</guid>
      <description>&lt;h2&gt;
  
  
  ❗ Avoid .Wait() and .Result in Async Contexts – Here’s Why
&lt;/h2&gt;

&lt;p&gt;Calling .Wait() or .Result on a Task blocks the current thread until the Task completes.&lt;br&gt;
In an async context (like a UI thread or ASP.NET request), this can cause a deadlock.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🧠 Why?&lt;/strong&gt;&lt;br&gt;
Async methods often capture the current synchronization context to resume on the same thread after an await.&lt;br&gt;
But if that thread is blocked by .Wait() or .Result, the continuation cannot resume.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The result:&lt;/strong&gt;&lt;br&gt;
The Task is waiting to resume on a thread that's blocked waiting for the Task&lt;br&gt;
➡️ &lt;strong&gt;Deadlock.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  💥 Example: Deadlock in a Console App (simulating UI behavior)
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DeadlockDemo
{
    public static void Main()
    {
        Console.WriteLine("Starting...");
        var result = GetData().Result; // ❌ This can deadlock in UI/ASP.NET
        Console.WriteLine($"Result: {result}");
    }

    public static async Task&amp;lt;string&amp;gt; GetData()
    {
        await Task.Delay(1000); // Simulate async work
        return "Hello from async!";
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What happens?&lt;br&gt;
In a real UI (WinForms/WPF) or ASP.NET context, Result can freeze the thread, causing a deadlock if the continuation needs to return to the UI thread.&lt;/p&gt;

&lt;h2&gt;
  
  
  ✅ The Right Way: Use await
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class AsyncSafeDemo
{
    public static async Task Main()
    {
        Console.WriteLine("Starting...");
        var result = await GetData(); // ✅ Safe and non-blocking
        Console.WriteLine($"Result: {result}");
    }

    public static async Task&amp;lt;string&amp;gt; GetData()
    {
        await Task.Delay(1000); // Simulate async work
        return "Hello from async!";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why this works:&lt;br&gt;
await allows the thread to remain free while waiting for the Task. The continuation is scheduled properly without blocking.&lt;/p&gt;

&lt;p&gt;❌ Avoid .Result or .Wait() in async contexts (can cause deadlocks).&lt;br&gt;
✅ Use await to keep things async and non-blocking.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Span&lt;T&gt; en C#</title>
      <dc:creator>Habib BARAKET</dc:creator>
      <pubDate>Thu, 22 May 2025 18:07:23 +0000</pubDate>
      <link>https://dev.to/habib_baraket/span-en-c-4ele</link>
      <guid>https://dev.to/habib_baraket/span-en-c-4ele</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwf0iu61vi2t42jdxp55c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwf0iu61vi2t42jdxp55c.png" alt="Span" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  ✅What Is Span?
&lt;/h2&gt;

&lt;p&gt;Span is a ref struct that enables you to efficiently and safely manipulate a contiguous region of memory (arrays, strings, native memory) without allocating any additional memory.&lt;/p&gt;

&lt;h2&gt;
  
  
  ❓ Why do we need Span?
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Avoid unnecessary memory allocations.&lt;/li&gt;
&lt;li&gt;Work with a portion of an array or a string without copying.&lt;/li&gt;
&lt;li&gt;Manipulate buffers or memory segments efficiently.&lt;/li&gt;
&lt;li&gt;Access stack memory via stackalloc for performance gains.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Declaring and Using Span
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;From an existing array or string
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Given an array
int[] numbers = { 10, 20, 30, 40, 50 };

// Create a Span&amp;lt;T&amp;gt; over the whole array
Span&amp;lt;int&amp;gt; allNums = numbers.AsSpan();

// Create a slice over elements 1–3 (20,30,40)
Span&amp;lt;int&amp;gt; middleNums = allNums.Slice(1, 3);

// You can read and write through the span:
middleNums[0] = 25;       // numbers[1] is now 25
Console.WriteLine(numbers[2]);  // prints 30

// For strings use ReadOnlySpan&amp;lt;char&amp;gt;
string text = "Hello, world!";
ReadOnlySpan&amp;lt;char&amp;gt; hello = text.AsSpan(0, 5);
Console.WriteLine(hello.ToString());  // "Hello"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;On the stack with stackalloc
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Allocate 8 ints on the stack (no heap allocation)
Span&amp;lt;int&amp;gt; stackBuf = stackalloc int[8];

// Initialize and use
for (int i = 0; i &amp;lt; stackBuf.Length; i++)
{
    stackBuf[i] = i * i;
}
Console.WriteLine(stackBuf[3]);  // prints 9

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;❓ Why do we need stackalloc?&lt;br&gt;
Since Span is a ref struct and lives on the stack, why do we need stackalloc to allocate a buffer on the stack?&lt;br&gt;
✅ Yes, Span itself lives on the stack (because it’s a ref struct)&lt;br&gt;
❌ But the data it points to is not automatically on the stack&lt;/p&gt;

&lt;p&gt;🔍 By default:&lt;br&gt;
&lt;code&gt;Span&amp;lt;byte&amp;gt; s = new byte[100];&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
➡️ Here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Span instance lives on the stack&lt;/li&gt;
&lt;li&gt;But the actual byte[100] array is allocated on the heap&lt;/li&gt;
&lt;li&gt;That allocation is managed by the garbage collector (GC)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;✅ With stackalloc:&lt;br&gt;
&lt;code&gt;Span&amp;lt;byte&amp;gt; s = stackalloc byte[100];&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;➡️ Now:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Both the Span and the 100 bytes of data are on the stack&lt;/li&gt;
&lt;li&gt;🧠 No heap allocation, and therefore no GC pressure&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Code&lt;/th&gt;
&lt;th&gt;Where is &lt;code&gt;Span&amp;lt;T&amp;gt;&lt;/code&gt;?&lt;/th&gt;
&lt;th&gt;Where is the data?&lt;/th&gt;
&lt;th&gt;GC involved?&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Span&amp;lt;byte&amp;gt; s = new byte[100];&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;📦 Stack&lt;/td&gt;
&lt;td&gt;🧠 Heap&lt;/td&gt;
&lt;td&gt;✅ Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Span&amp;lt;byte&amp;gt; s = stackalloc byte[100];&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;📦 Stack&lt;/td&gt;
&lt;td&gt;📦 Stack&lt;/td&gt;
&lt;td&gt;❌ No&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  ⛔ Limitations of Span
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;💥 Why can't Span be a field in a class?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Class instances live on the heap.&lt;/li&gt;
&lt;li&gt;Span is a ref struct, which means it must live on the stack and is not allowed to be stored on the heap.&lt;/li&gt;
&lt;li&gt;If a Span were stored in a class field, it could keep referencing stack memory that is no longer valid once the method exits.&lt;/li&gt;
&lt;li&gt;This would lead to undefined behavior, potential memory corruption, and security risks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;💥Why is Span not allowed in yield return,async methods or lambdas?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;yield return, async and lambda expressions are also compiled into state machines that live on the heap.&lt;/li&gt;
&lt;li&gt;Variables from inside the async/lambda context are often captured and stored on the heap as part of the closure or state machine.&lt;/li&gt;
&lt;li&gt;If a Span were captured this way, it would leak a reference to stack memory into a heap object.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;❌ This violates memory safety and lifetime guarantees, so the compiler blocks this usage.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>memory</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
