Threads, Tasks, Parallel and Thread Safety

Dot NET Programming 15 min min read Updated: Nov 16, 2026 Advanced
Threads, Tasks, Parallel and Thread Safety
Advanced Topic 2 of 6

Concurrency vs Parallelism

TermMeaningTool
AsynchronousDo not block while waiting for I/Oasync / await
ParallelUse many CPU cores at the same time for heavy calculationsParallel, Task.Run

Task.Run: Move Work Off the Current Thread

csharp long CountPrimes(int max) { long count = 0; for (int n = 2; n <= max; n++) { bool prime = true; for (int d = 2; d * d <= n; d++) if (n % d == 0) { prime = false; break; } if (prime) count++; } return count; } long result = await Task.Run(() => CountPrimes(200_000)); Console.WriteLine(result);

Parallel Loops

csharp var numbers = Enumerable.Range(1, 1_000_000).ToArray(); Parallel.For(0, numbers.Length, i => { numbers[i] = numbers[i] * 2; // each index touched by only one thread: safe }); await Parallel.ForEachAsync(urls, new ParallelOptions { MaxDegreeOfParallelism = 4 }, async (url, token) => { using var client = new HttpClient(); var text = await client.GetStringAsync(url, token); Console.WriteLine($"{url}: {text.Length}"); }); string[] urls = ["https://example.com", "https://example.org"];

Race Conditions

When two threads change the same variable at the same time, results become wrong.

csharp int counter = 0; Parallel.For(0, 100_000, _ => counter++); // NOT safe Console.WriteLine(counter); // usually less than 100000

Fix 1: lock

csharp int counter = 0; var gate = new Lock(); // System.Threading.Lock (.NET 9 and later) Parallel.For(0, 100_000, _ => { lock (gate) { counter++; } }); Console.WriteLine(counter); // 100000

Fix 2: Interlocked for Simple Numbers

csharp int counter = 0; Parallel.For(0, 100_000, _ => Interlocked.Increment(ref counter));

Thread-Safe Collections

csharp using System.Collections.Concurrent; var wordCounts = new ConcurrentDictionary<string, int>(); Parallel.ForEach(new[] { "a", "b", "a", "c", "a" }, word => { wordCounts.AddOrUpdate(word, 1, (key, old) => old + 1); }); Console.WriteLine(wordCounts["a"]); // 3

Producer and Consumer with Channel

csharp using System.Threading.Channels; var channel = Channel.CreateBounded<int>(10); var producer = Task.Run(async () => { for (int i = 1; i <= 5; i++) await channel.Writer.WriteAsync(i); channel.Writer.Complete(); }); var consumer = Task.Run(async () => { await foreach (int item in channel.Reader.ReadAllAsync()) Console.WriteLine($"Processed {item}"); }); await Task.WhenAll(producer, consumer);
Shared state is the enemy: Prefer designs where each thread works on its own data. Use locks only when you must share, and keep the locked section as short as possible.

Conclusion

Use Task.Run and Parallel for CPU work, protect shared variables with lock, Interlocked or concurrent collections and use Channel to pass work between producers and consumers.

Quick Summary: Parallel for CPU, lock or Interlocked for shared data, ConcurrentDictionary and Channel for safe sharing.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators