LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 4518 min read

Multithreading Basics

Learn the basics of running code in parallel using threads and the Task Parallel Library in C#.

What is Multithreading?

Multithreading runs multiple pieces of code truly simultaneously across CPU cores, ideal for CPU-intensive work — as opposed to async/await, which is about not blocking a thread while waiting on I/O.

Creating a Thread

using System.Threading;
Thread thread = new Thread(() =>
{
Console.WriteLine("Running on a separate thread!");
});
thread.Start();
thread.Join(); // wait for it to finish

Task Parallel Library

In modern C#, `Parallel.For` and `Parallel.ForEach` from the Task Parallel Library (TPL) are the recommended way to parallelize CPU-bound work, rather than managing raw threads by hand.

Parallel.For(0, 5, i =>
{
Console.WriteLine($"Processing item {i} on thread {Thread.CurrentThread.ManagedThreadId}");
});

Thread Safety

When multiple threads access shared data at the same time, you can get race conditions — unpredictable results from unsynchronized access. The `lock` keyword ensures only one thread can execute a block of code at a time.

object lockObject = new object();
int counter = 0;
Parallel.For(0, 1000, i =>
{
lock (lockObject)
{
counter++; // safe — only one thread at a time
}
});
Console.WriteLine(counter); // reliably 1000

FAQs

No — threads have overhead, and web apps built on ASP.NET Core mostly rely on async/await instead. Reach for explicit multithreading only for genuinely CPU-bound parallel work.

Summary

  • Multithreading runs code truly in parallel across CPU cores.
  • The Task Parallel Library (Parallel.For/ForEach) is the modern, recommended approach.
  • Use `lock` to protect shared data from race conditions across threads.
Next Lesson →

Unit Testing Basics