← Foundations path
.NETFoundations 17 / 37

Threads and thread-safety

“What is a thread, and what makes code thread-safe?”

One line of work the computer runs. A web app runs many at once, and they all share your singletons.

See it

Threadsmany run at onceOne singletonshared by every requestthread poolthread 1: Athread 2thread 3the repositoryInMemoryLoanRepositoryDictionary<Guid, Loan>slot 6 → loan Xslot 7 freeA: waiting, holds no thread2,000 POSTs → 9 to 15 lost
1 / 8A thread is one line of work. It runs code one statement after another, like request A here.

In plain words

A thread is one line of work: the computer runs its code one statement after another. A web app runs many threads at once, one for each busy request. If those threads share one object and two change it at the same moment, they spoil each other's work. Thread-safe code still works correctly when that happens.

Say it in the interview

In the lending API

The bug, the fix, and the test that catches it. Press Next line to walk through them.

Lending.sln · where these 3 files sit
  • src/Infrastructure/Servicing/
  • tests/Infrastructure.UnitTests/
Diagram · step 3All three call the same : one object, one dictionary, shared by every thread.
Threadsmany run at onceOne singletonshared by every requestthread poolthread 1: Athread 2thread 3the repositoryInMemoryLoanRepositoryDictionary<Guid, Loan>slot 6 → loan Xslot 7 freeA: waiting, holds no thread2,000 POSTs → 9 to 15 lost
InMemoryLoanRepository.old.cs · line 7 · 1 of 6Registered with in Program.cs, so the app builds one of these and every request on every thread uses it. See .

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

With AI tools

AI tools often write an in-memory repository or cache as a plain or inside a singleton. It compiles and passes one-user tests. Interviews now include reviewing AI-written code, and "this shared collection is not thread-safe" is the catch they expect.

Read more: Microsoft Learn: thread-safe collections · Microsoft Learn: ConcurrentDictionary · Managed threading best practices · Microsoft Learn: Parallel.For