惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
B
Blog RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
SegmentFault 最新的问题
Y
Y Combinator Blog
月光博客
月光博客
IT之家
IT之家
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
L
LangChain Blog
博客园_首页
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
博客园 - Franky
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
V
Visual Studio Blog
小众软件
小众软件
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Ensuring Thread Safety — .NET core-centric
Hossein Esmati · 2026-06-26 · via DEV Community

Hossein Esmati

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 a single-threaded “actor” that owns its state. Or use an external queue/bus so workers don’t share memory.

Why: Eliminates shared writes; logic becomes “handle one message at a time.”

How (lightweight actors with Channels):

public sealed class CounterActor
{
    private readonly Channel<Action<State>> _in = Channel.CreateUnbounded<Action<State>>();
    private readonly State _state = new();

    public CounterActor()
    {
        _ = Task.Run(async () =>
        {
            await foreach (var msg in _in.Reader.ReadAllAsync())
                msg(_state); // single-threaded access
        });
    }

    public ValueTask Tell(Action<State> msg) => _in.Writer.WriteAsync(msg);

    public sealed class State { public int Count; }
}

At scale: use Orleans/Akka.NET (virtual actors) or external queues (Azure Service Bus/Storage Queues) to process messages concurrently without shared memory.

Timeouts, cancellation, and async correctness

  • Always pass CancellationToken so long operations end promptly—reduces lock contention.
  • In ASP.NET Core, never block the thread (.Result, .Wait()); use await to avoid thread pool starvation.

Observability for thread-safety issues

  • Metric: lock contention, queue length, actor mailbox size.
  • Logs with correlation IDs to trace races.
  • Load/stress tests that hammer critical paths (many parallel tasks) to catch races early.

Quick decision guide

  • Can it be immutable? Do that first.
  • Must it be shared & mutable? Encapsulate state behind an actor or a queue.
  • Tiny unavoidable mutation? Guard with Interlocked/lock/SemaphoreSlim (short, ordered, no I/O).
  • Collections? Prefer immutable or Concurrent* types.