Skip to content
dreamcode
dreamcode
Map
Concurrency
Lesson 20 of 21
+15 XP on finish
C# EXPERTChapter 6 · C# Expert

Thread safety and lock synchronization

The Task Parallel Library (TPL) executes tasks concurrently. When threads modify shared state, use the lock statement to restrict critical region access to one thread at a time.

Worked example
using System;
using System.Threading.Tasks;

class Program {
    static readonly object _lock = new object();
    static int _count = 0;

    static void Main() {
        Parallel.For(0, 100, i => {
            lock (_lock) {
                _count++;
            }
        });
        Console.WriteLine(_count);
    }
}

How it reads

  • lock (_lock) ensures only one thread enters the body block at a time
  • Parallel.For executes actions in parallel using multiple threads
Cloud tip: Only lock reference types (usually a private dedicated object), never lock value types or strings.

Check your understanding

0 / 2

Answer all 2 to complete this lesson and earn 15 XP.

  1. 1. What can happen if two threads lock resources in a circular dependency order?
  2. 2. Which keyword guarantees mutual exclusion across C# threads?
Answer every question to unlock the next lesson.