Introduction
When someone says “this service is thread-safe”, the sentence states something simple and serious: it can be accessed by multiple threads at the same time without causing state corruption, intermittent results or race conditions. In production, this is an architecture matter, not just academic curiosity. A Singleton with an internal Dictionary can work in tests and fail in production under load. A shared cache without concurrency control can lose items without any visible error. And the problem is not new: it follows web applications, workers, queues, background services and batch processing.
The goal of this article is to show exactly how this happens on two platforms widely used in the modern ecosystem: .NET 10 and Python. In .NET, the answer usually involves System.Threading.Lock, Interlocked, ConcurrentDictionary and DI lifetime choices. In Python, the conversation quickly moves to the GIL (Global Interpreter Lock), the threading model, queue.Queue and, today, a more relevant scenario: free-threaded Python, which removes part of that guarantee and hands the developer direct responsibility for synchronization.
The good news is that the reasoning is the same on both sides: shared mutable state requires protection or the elimination of sharing. If the state is immutable, things get simpler. If the state is shared and mutable, you need to think about invariants, atomic access and testability. That is what I will show here with practical examples and with a test pattern that proves whether the service really withstands concurrency.
⚠️ Warning: The problem is not “many threads at the same time” by itself. The problem is simultaneous access to shared state without a synchronization rule. Without that detail, any service can look stable in a lab environment and break under real load.

What thread-safe means in practice
Thread-safe is a property of the component’s behavior, not just of the language. An implementation is thread-safe when, under any valid interleaving of threads, the data structure and the observable behavior remain consistent. In other words: the object stays correct even when two or more threads try to use the same resource at the same time.
To make it more concrete, think of a simple counter:
| |
This code looks trivial. In practice, ++ on an integer is not an atomic operation. The real sequence is something like: read the value, add 1, write it back. If two threads do this at the same time, both can read the same old value and write the same final result. The counter “loses” an increment, and the failure is called a race condition.
This matters because many production services have shared state in a Singleton, an in-memory cache, a statistics accumulator, batch processing and queues. When that happens without synchronization, the problem is not just theoretical — it shows up as inconsistent counters, partially filled lists, broken dictionaries or intermittent errors that look random.
Four properties that matter
When you work with concurrency, you usually want to answer four questions:
- Can the state be accessed by multiple threads at the same time?
- Does this operation have atomic semantics?
- Do reads and writes have consistent visibility across threads?
- Does the mutation preserve the object’s invariants?
If the answer to the first is “yes”, you need to consider synchronization or immutability. The x++ operation fails the first and the second. ConcurrentDictionary tries to solve this without requiring a manual lock on each operation. Interlocked solves the simplest case of a counter or atomic value.
.NET 10: what changed and when to use System.Threading.Lock
In .NET, the classic way to protect a block was to use lock on an object: lock (_lock) { ... }. That works, but the old pattern lets the developer write synchronization support in a not very explicit way. Starting with .NET 9, the standard library began offering the System.Threading.Lock type, which makes the intent clearer.
| |
The idea of Lock is very similar to the traditional lock, but the API has a more explicit intent and helps avoid synchronization pitfalls with naively chosen objects. That matters because lock (this) or lock (new object()) often cause real bugs in architecture. Lock also makes the code more readable and more specific about what it is protecting.
When to use lock and when to use Interlocked
The practical rule is simple:
- use
lockwhen you need to protect a block of code with multiple operations and more complex invariants; - use
Interlockedwhen you only need to protect a primitive variable with a simple operation.
Example with Interlocked:
| |
Interlocked operates at a lower level and avoids unnecessary contention in simple operations. It is especially useful for counters, state flags and fast synchronization rules. lock, on the other hand, remains the right tool when correctness requires isolating a sequence of steps and ensuring that the whole operation runs indivisibly.
ConcurrentDictionary and concurrent collections
An important part of thread-safety in .NET lives in the collections of the System.Collections.Concurrent namespace.
| |
This pattern is used in cache services and concurrent aggregations. The idea is that the structure already knows how to synchronize writes and reads internally. That is much better than a shared Dictionary accessed by several threads, especially in high-load scenarios. In a singleton, a regular Dictionary is a classic trap. In a Scoped or Transient service, it usually will not require synchronization because the object will not be shared across requests.
DI in ASP.NET Core: Singleton is the critical point
The ASP.NET Core DI container changes the rules of the game. The service lifetime defines whether the same object will be shared by multiple requests or not.
Practical rule
AddSingleton— the same object lives for the whole application. If it has mutable state, it must be thread-safe.AddScoped— usually each request gets its own instance. In general, it does not require thread-safety.AddTransient— creates one instance per injection. In general, it also does not require thread-safety.
That is straightforward, but the dangerous part is this: many people register an “in-memory cache” as a singleton because it looks simple, but then the same object is queried and updated by multiple requests at the same time. The design leads to race conditions, unexpected KeyNotFoundException, an exposed mutable list, or simply inconsistent data.
A classic example:
| |
This service looks harmless, but it is not thread-safe. If the same instance is used by multiple requests simultaneously, mutating the Dictionary causes real problems. The fix is to use ConcurrentDictionary, ImmutableDictionary or to encapsulate the mutation in a lock when the operation requires a sequence of steps.
ℹ️ Info:
DbContextshould never be a singleton by design. It is not thread-safe and was not designed to be shared across requests.
Python: the GIL and the world where it does not solve everything
In Python, the scenario is different. The CPython interpreter uses the GIL (Global Interpreter Lock), which serializes bytecode execution in each process. In other words, on the same machine with the standard interpreter, the language prevents two Python threads from interpreting bytecode at the same time.
This creates a recurring myth: “if Python has the GIL, then the application is thread-safe by default”. That is false. The GIL does not solve compound invariants and does not make code thread-safe in an architectural sense. It only prevents simultaneous execution of Python bytecode within the same process.
The GIL helps in I/O-bound scenarios, such as network calls, files and sockets, because one thread can wait while another runs. But it does not protect a shared mutable object when the real operation requires several steps, and it gives no consistency guarantee for complex mutable structures.
Classic example in Python:
| |
This code looks simple, but it is not atomically safe in terms of program semantics. The GIL does not guarantee that the whole read + compute + write sequence happens without interference. Implementation details may vary, and correctness requires explicit synchronization with threading.Lock or a structure designed for concurrency.
Python 3.13 and free-threaded mode
The Python community has discussed the idea of removing the GIL or making it optional for a long time. In 2023/2024, the project reached a more realistic stage with free-threaded Python (or Python running without the GIL), an important change for the ecosystem. It means that, in some builds, multiple threads can execute Python bytecode in parallel, which brings the synchronization problem back to the center of the discussion.
In other words:
- with the GIL, concurrency in Python still requires care;
- without the GIL, the need for explicit synchronization becomes more obvious;
- real day-to-day engineering remains the same: protect shared state and test invariants.
Concurrency primitives in Python
Python offers well-known options:
| |
There are also:
threading.RLock— reentrant lock;threading.Semaphore— limits concurrent access;threading.Event— signaling between threads;queue.Queue— thread-safe queue for producer/consumer communication;concurrent.futures— runs tasks in a pool of threads or processes.
These tools are conceptually equivalent to what .NET offers, but the runtime semantics change. In Python, especially in CPython, the GIL architecture and the presence of free-threaded mode can change the level of parallelism and the design guidance.
Side-by-side comparison: .NET 10 vs Python
The table below helps with the practical analysis:
| Need | .NET 10 | Python |
|---|---|---|
| Simple locking | System.Threading.Lock | threading.Lock |
| Atomic counter | Interlocked.Increment | threading.Lock or itertools.count |
| Concurrent dictionary | ConcurrentDictionary | dict with lock or queue |
| Concurrency limit | SemaphoreSlim | threading.Semaphore |
| Producer/consumer queue | Channel<T> | queue.Queue / asyncio.Queue |
| Immutable state | ImmutableDictionary | frozenset, tuple, MappingProxyType |
| Asynchronous parallelism | Task, await | asyncio, ThreadPoolExecutor |
| CPU-bound processing | Parallel.ForEach, Task | ProcessPoolExecutor |
The main conceptual difference is this: in .NET, the threading model and the memory model are more explicit; in Python, the existence of the GIL and the cooperative asyncio model create more layers of abstraction. But, in both cases, the problem is the same: synchronization must exist when you have shared mutable state.
How to test whether a service is thread-safe
The best way to test is not to “look at the code” and decide it seems safe. The best way is to build a stress test with multiple threads, run many operations and validate an invariant. The pattern is simple: N threads, K iterations, an expected total and an assertion guaranteeing that the final value is always the same.
In .NET, it looks like this:
| |
If the implementation is unsafe, the final total will be lower than expected in some runs. That is typical of a race condition: the problem appears probabilistically and intermittently. Running it once is not enough. It is worth repeating several rounds to validate.
That is exactly what the blog’s samples repository demonstrates: an unprotected service, a service with Lock and a service with Interlocked. The same pattern is easy to repeat in Python with threading.Thread and threading.Lock.
📂 Source Code: The complete example is available in the blog’s samples repository:
BlogSamples/AsyncParallel/ThreadSafety/
Practical example in C#
Below is a minimal example with two versions of the same service: an unsafe one and a safe one. The goal here is not to show a complete framework; it is to demonstrate the concept precisely.
| |
The structure above already explains a lot. The unsafe version loses increments under concurrency; the protected version keeps the value consistent. The next step, in a real service, is deciding whether the right solution is lock, Interlocked, ConcurrentDictionary or full immutability. That depends on the type of operation and on how much mutation the object needs to support.
Realistic example: ConcurrentDictionary in a singleton
A singleton that aggregates statistics is a classic case of correct ConcurrentDictionary usage:
| |
This pattern is very useful when the application records events, metrics, counters per user or per endpoint. The structure already implements internal synchronization, so the service can remain a singleton without becoming a source of race conditions.
Tips and good practices
- Prefer immutability whenever possible. Immutable objects are easier to share without synchronization.
- In .NET 10, prefer
System.Threading.Lockin complex blocks instead of using arbitrary objects as synchronizers. - In a
Singleton, assume that mutable state needs protection; inScopedandTransient, most instances are not shared. - In Python, the
GILis not the same thing as thread-safety; always synchronize when shared state is mutable. - Test concurrency with multiple threads and assertions about invariants, not just with simple unit execution.
- When the pattern requires it for every operation, use
ConcurrentDictionary,Channel<T>or queues instead of exposedDictionaryandList. - Return snapshots when exposing internal state for reading; avoid returning mutable dictionaries or lists from the shared object.
Objective Summary
- Thread-safety — the guarantee that a component keeps a consistent state even under simultaneous access by multiple threads.
System.Threading.Lockin .NET 10 — offers an explicit and more readable primitive to protect code blocks and complex invariants.Interlocked— ideal for simple counters and atomic single-variable operations, without locking the whole system.Singletonin ASP.NET Core — requires extra attention because the same service can serve multiple requests in parallel.DictionaryandListin a singleton — classic examples of code that works in tests and fails in production under load.- The GIL in Python — helps in some situations, but does not replace synchronization of shared state nor eliminate race conditions.
- Free-threaded Python — reinforces even more that explicit synchronization remains the developer’s responsibility.
- Concurrency test — N threads × K iterations with an invariant check is the most reliable way to determine whether the service really withstands load.
Read Also
- Asynchronous Programming in C#: async/await and Threads
- Parallelism in C#: Parallel, PLINQ and Tasks in Practice
- .NET Worker and Background Service: High Volume
- Comparing C# with Other Modern Languages
- pip Is Slow, Poetry Is Complex: UV Arrived to Fix Python

By commenting, you agree to our Privacy Policy, Terms of Use, Data Deletion Policy.