今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

Ensuring Thread Safety — .NET core-centric

Hossein Esmati 2026年06月26日 20:35 5 次阅读 来源:Dev.to

Prefer immutability What: Make data read-only after construction. Instead of editing objects, create new ones. Why: If nothing changes, many threads can read safely with no locks . How (.NET): public readonly record struct Money ( decimal Amount , string Currency ); public record Order ( Guid Id , IReadOnlyList < OrderLine > Lines ) { public Order AddLine ( OrderLine line ) => this with { Lines = Lines . Append ( line ). ToList () }; } Use record / readonly struct , IReadOnlyList<> , and with (copy-on-write). Keep collections immutable ( ImmutableList<T> , ImmutableDictionary<K,V> ). Avoid shared state What: Don’t let unrelated code touch the same mutable object. Why: If each operation owns its data, there’s nothing to synchronize. How: Per-request scope : create new service instances that hold request-specific state. No static mutable fields; if you must cache, use ConcurrentDictionary : private static readonly ConcurrentDictionary < string , Widget > _cache = new (); var widget = _cache . GetOrAdd ( key , k => LoadWidget ( k )); Use lock / SemaphoreSlim cautiously What: Synchronization primitives that serialize access to critical sections. When: Short, minimal critical sections where mutation is unavoidable. lock for synchronous code; SemaphoreSlim when await is involved (never block in async code). Patterns & pitfalls: private readonly object _gate = new (); void Update () { lock ( _gate ) // keep work tiny inside { // mutate a small piece of shared state _count ++; } } private readonly SemaphoreSlim _sem = new ( 1 , 1 ); async Task UpdateAsync () { await _sem . WaitAsync (); try { _count ++; } finally { _sem . Release (); } } Never lock(this) or a public object (external code could deadlock you). Keep lock duration short; avoid I/O under locks. If multiple locks are needed, fix a global order to prevent deadlocks. Atomic counters (avoid locks entirely): Interlocked . Increment ( ref _count ); Leverage actor-style or message queues What: Push work as messages to

本文内容来源于互联网,版权归原作者所有
查看原文