Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C# Locking Patterns: Deadlock, Race Conditions, and Thread-Safe Code

- 22.08.26 - ErcanOPAK

🧵 Key Takeaways: Master async/await locking, avoid deadlocks, prevent race conditions, and write truly thread-safe code with modern C# patterns.

Multithreading is hard. Race conditions and deadlocks are lurking. Here’s how to conquer them.

❌ Common Anti-Patterns

// ❌ Race Condition
public class Counter
{
    private int _value;
    public void Increment() => _value++;  // ❌ Not atomic!
    public int Value => _value;
}

// ❌ Deadlock (lock ordering)
public class BankAccount
{
    private readonly object _lock = new();
    public void Transfer(BankAccount target, decimal amount)
    {
        lock (_lock)
        {
            lock (target._lock) // ❌ Deadlock if two threads transfer opposite directions!
            {
                // Transfer logic
            }
        }
    }
}

// ❌ Async deadlock (sync over async)
public async Task<string> GetDataAsync()
{
    return await _httpClient.GetStringAsync("https://api.com");
}
public string GetData()
{
    return GetDataAsync().Result; // ❌ Deadlock in ASP.NET Core!
}

✅ Correct Patterns

// ✅ 1. Lock with Monitor
public class ThreadSafeCounter
{
    private readonly object _lock = new();
    private int _value;

    public void Increment()
    {
        lock (_lock)  // ✅ Thread-safe
        {
            _value++;
        }
    }
}

// ✅ 2. SemaphoreSlim for Async
public class AsyncThrottledService
{
    private readonly SemaphoreSlim _semaphore = new(10, 10); // 10 concurrent

    public async Task<string> ProcessAsync(string data)
    {
        await _semaphore.WaitAsync();
        try
        {
            // ✅ Only 10 concurrent operations
            return await ProcessDataAsync(data);
        }
        finally
        {
            _semaphore.Release();
        }
    }
}

// ✅ 3. ReaderWriterLockSlim (Read-heavy)
public class Cache<TKey, TValue> where TKey : notnull
{
    private readonly ReaderWriterLockSlim _lock = new();
    private readonly Dictionary<TKey, TValue> _cache = new();

    public TValue Get(TKey key)
    {
        _lock.EnterReadLock();
        try
        {
            return _cache.TryGetValue(key, out var value) ? value : default;
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }

    public void Set(TKey key, TValue value)
    {
        _lock.EnterWriteLock();
        try
        {
            _cache[key] = value;
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }
}

// ✅ 4. Concurrent Collections (Best!)
public class ConcurrentCache<TKey, TValue>
{
    private readonly ConcurrentDictionary<TKey, TValue> _cache = new();

    public TValue GetOrAdd(TKey key, Func<TKey, TValue> factory)
    {
        return _cache.GetOrAdd(key, factory); // ✅ Thread-safe!
    }
}

💡 Pro Tip: AsyncLock Pattern

// ✅ Custom AsyncLock for async/await locking
public class AsyncLock
{
    private readonly SemaphoreSlim _semaphore = new(1, 1);

    public async Task<IDisposable> LockAsync()
    {
        await _semaphore.WaitAsync();
        return new Releaser(_semaphore);
    }

    private class Releaser : IDisposable
    {
        private readonly SemaphoreSlim _semaphore;

        public Releaser(SemaphoreSlim semaphore)
        {
            _semaphore = semaphore;
        }

        public void Dispose()
        {
            _semaphore.Release();
        }
    }
}

// Usage
public class AsyncService
{
    private readonly AsyncLock _lock = new();

    public async Task ProcessAsync()
    {
        using (await _lock.LockAsync())
        {
            // ✅ Only one thread at a time
            await SomeAsyncOperationAsync();
        }
    }
}

🔍 Deadlock Prevention

// ✅ 1. Consistent lock order
public void Transfer(BankAccount target, decimal amount)
{
    var lock1 = this._lock;
    var lock2 = target._lock;
    
    if (this.GetHashCode() > target.GetHashCode())
    {
        lock1 = target._lock;
        lock2 = this._lock;
    }
    
    lock (lock1)
    {
        lock (lock2)
        {
            // ✅ Always same order - No deadlock!
        }
    }
}

// ✅ 2. Use Monitor.TryEnter with timeout
public bool TryTransfer(BankAccount target, decimal amount, int timeoutMs)
{
    if (!Monitor.TryEnter(this._lock, timeoutMs)) return false;
    try
    {
        if (!Monitor.TryEnter(target._lock, timeoutMs)) return false;
        try
        {
            // Transfer logic
            return true;
        }
        finally { Monitor.Exit(target._lock); }
    }
    finally { Monitor.Exit(this._lock); }
}

// ✅ 3. Use SemaphoreSlim with timeout
var semaphore = new SemaphoreSlim(1, 1);
if (await semaphore.WaitAsync(TimeSpan.FromSeconds(5)))
{
    try { /* Critical section */ }
    finally { semaphore.Release(); }
}

Related posts:

C# LINQ Looks Clean but Allocates Heavily

C# LINQ Looks Clean but Allocates Heavily

Middleware Order Can Break Security

Middleware Order Can Break Security

C#: Real-world LINQ Query Examples

C#: Real-world LINQ Query Examples

Views: 8

Post navigation

YARP (.NET Reverse Proxy): Build Your Own API Gateway in Minutes
OWASP Top 10 in .NET: How to Protect Your Web Application from the Most Critical Security Risks

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com