🧵 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(); }
}

