C# Thread
last modified November 15, 2026
This tutorial covers threading in C# with the Thread class. We
start and join threads, pass them data, use foreground and background threads,
protect shared data, and stop threads cooperatively.
A process is an instance of a running program with its own memory and system resources. When a .NET process starts, the runtime creates the main foreground thread, which executes the application code. A process can contain multiple threads, each representing a distinct path of execution within the program. The threads of a process share its memory.
In C#, the Thread class from the System.Threading
namespace creates and controls threads. It lets us start threads, wait for
them, set their names and priorities, and query their state.
Processes and threads are both independent sequences of execution, but they differ in memory usage and performance characteristics. The following table highlights key differences between them:
| Process | Thread |
|---|---|
| Runs in separate memory space (process isolation) | Shares memory with other threads within the same process |
| Consumes more memory | Consumes less memory |
| Higher overhead for resource management | Lower overhead, more lightweight |
| Slower to create and terminate | Faster to create and terminate |
| Isolated, communicates through interprocess communication | Communicates through shared memory, which requires synchronization |
| A crash usually affects only the process itself | An unhandled exception in any thread terminates the whole process |
In modern .NET code, most concurrent work is done with tasks
(Task.Run, async and await), which run
on the thread pool. A dedicated Thread is still useful for
long-running work, for threads which need special settings, and for
understanding what tasks do under the hood. The output of the examples in this
article varies from run to run, because the operating system decides when each
thread runs.
C# Thread Start
The Start method starts a thread.
Console.WriteLine("main started");
var id = Environment.CurrentManagedThreadId;
Console.WriteLine($"main id: {id}");
var t = new Thread(Task);
t.Start();
Console.WriteLine("main finished");
void Task()
{
Console.WriteLine("thread started");
var id = Environment.CurrentManagedThreadId;
Console.WriteLine($"thread id: {id}");
}
A new thread is created and then launched with Start.
var id = Environment.CurrentManagedThreadId;
Console.WriteLine($"main id: {id}");
The Environment.CurrentManagedThreadId property returns a unique
identifier of the current managed thread. It is a shorter equivalent of
Thread.CurrentThread.ManagedThreadId.
var t = new Thread(Task);
A new Thread is created. We pass it the method to execute. The
thread does not run until we call Start.
t.Start();
The thread is started. Start returns immediately and the main
thread continues while the new thread runs.
In the output, the main thread has finished before the other thread. Still, the program waits for the thread to complete, because it is a foreground thread.
$ dotnet run main started main id: 1 main finished thread started thread id: 4
C# Thread pass arguments
The simplest way to pass data to a thread is a lambda expression which calls a
method with the required arguments. The Start method also has an
overload which passes a single object argument.
int n = 3;
string word = "falcon";
var t1 = new Thread(() => Repeat(n, word));
t1.Start();
t1.Join();
var t2 = new Thread(obj => Console.WriteLine($"received: {obj}"));
t2.Start("hawk");
t2.Join();
void Repeat(int n, string word)
{
for (int i = 0; i < n; i++)
{
Console.WriteLine(word);
}
}
The first thread prints a word n times, the second prints the object it receives.
var t1 = new Thread(() => Repeat(n, word));
The lambda captures the n and word variables and
calls the Repeat method with them. The arguments are type-checked
by the compiler.
var t2 = new Thread(obj => Console.WriteLine($"received: {obj}"));
t2.Start("hawk");
Here the lambda matches the ParameterizedThreadStart delegate,
which takes an object? parameter. The value passed to
Start is handed to it. This older style requires casts for
anything but printing.
t1.Join();
We wait for each thread to finish, so the output is printed in a fixed order.
$ dotnet run falcon falcon falcon received: hawk
C# Thread.Sleep
The Thread.Sleep method suspends the current thread for the
specified number of milliseconds or for a TimeSpan. In examples,
it is often used to simulate a long-running task.
for (int i = 0; i < 5; i++)
{
var n = Random.Shared.Next(500, 1500);
var t = new Thread(() => Task(n));
t.Start();
}
void Task(int n)
{
var id = Environment.CurrentManagedThreadId;
Console.WriteLine($"thread id: {id} started");
Thread.Sleep(n);
Console.WriteLine($"thread id: {id} finished in {n} ms");
}
In the program, we create five threads that sleep for a random number of milliseconds.
var n = Random.Shared.Next(500, 1500);
We create a random number between 500 and 1499. Random.Shared is
a thread-safe instance of the Random class.
var t = new Thread(() => Task(n)); t.Start();
We pass the random number to the newly created thread. The n
variable is declared inside the loop body, so each lambda captures its own
copy.
Thread.Sleep(n);
The thread suspends its execution for n milliseconds. A sleeping thread uses no CPU time. The threads finish in the order of their sleep times, not in the order in which they were started.
$ dotnet run thread id: 6 started thread id: 4 started thread id: 5 started thread id: 8 started thread id: 7 started thread id: 6 finished in 614 ms thread id: 4 finished in 1025 ms thread id: 7 finished in 1105 ms thread id: 5 finished in 1122 ms thread id: 8 finished in 1403 ms
C# foreground & background thread
There are two kinds of threads: foreground and background. Background threads do not keep a process alive. When all foreground threads of a process have terminated, the runtime ends the process and stops all background threads.
A new thread is a foreground thread by default. We change it to a background
thread with the IsBackground property.
bool background = args.Length == 0 || args[0] != "fg";
Console.WriteLine($"started main, background threads: {background}");
for (var i = 0; i < 5; i++)
{
var rn = Random.Shared.Next(500, 1500);
var t = new Thread(() => Task(rn));
t.IsBackground = background;
t.Start();
}
Console.WriteLine("finished main");
void Task(int n)
{
Thread.Sleep(n);
var id = Environment.CurrentManagedThreadId;
Console.WriteLine($"{id} finished in {n} ms");
}
The program starts five threads. By default, they are background threads;
with the fg command line argument, they are foreground threads.
bool background = args.Length == 0 || args[0] != "fg";
In top-level statements, the command line arguments are available in the
args variable.
t.IsBackground = background;
The property must be set before the thread is started.
In the first run, the main thread is the only foreground thread. When it finishes, the process ends and the sleeping background threads are terminated before they print anything. In the second run, the process waits for the five foreground threads to complete.
$ dotnet run started main, background threads: True finished main $ dotnet run fg started main, background threads: False finished main 7 finished in 942 ms 8 finished in 1099 ms 5 finished in 1127 ms 6 finished in 1240 ms 4 finished in 1431 ms
C# Thread Join
The Join method blocks the calling thread until the specified
thread terminates.
Console.WriteLine("main started");
Thread[] threads = new Thread[5];
for (int i = 0; i < threads.Length; i++)
{
var n = Random.Shared.Next(500, 1500);
threads[i] = new Thread(() => Task(n));
}
foreach (var thread in threads)
{
thread.Start();
}
foreach (var thread in threads)
{
thread.Join();
}
Console.WriteLine("main finished");
void Task(int n)
{
var id = Environment.CurrentManagedThreadId;
Console.WriteLine($"thread id: {id} started");
Thread.Sleep(n);
Console.WriteLine($"thread id: {id} finished in {n} ms");
}
In this program, the main thread waits for all other threads to finish.
foreach (var thread in threads)
{
thread.Start();
}
First, we start all five threads, so they run concurrently.
foreach (var thread in threads)
{
thread.Join();
}
Then we join them. Join on a thread which has already finished
returns immediately; the loop ends when the slowest thread is done. Starting
and joining each thread in the same loop would run the threads one after
another.
$ dotnet run main started thread id: 4 started thread id: 8 started thread id: 5 started thread id: 6 started thread id: 7 started thread id: 8 finished in 521 ms thread id: 4 finished in 795 ms thread id: 5 finished in 1163 ms thread id: 7 finished in 1248 ms thread id: 6 finished in 1422 ms main finished
Join with timeout
The Join method has overloads which take a timeout. They return
true if the thread has terminated and false if the
time has elapsed first.
var t = new Thread(() => Thread.Sleep(2000));
t.Start();
bool finished = t.Join(500);
Console.WriteLine($"finished within 500 ms: {finished}");
Console.WriteLine($"state: {t.ThreadState}");
finished = t.Join(TimeSpan.FromSeconds(3));
Console.WriteLine($"finished within 3 s: {finished}");
Console.WriteLine($"state: {t.ThreadState}");
The thread sleeps for two seconds. We wait for it twice with a different timeout.
bool finished = t.Join(500);
Console.WriteLine($"finished within 500 ms: {finished}");
Console.WriteLine($"state: {t.ThreadState}");
After half a second, the thread is still sleeping. The
ThreadState property reports WaitSleepJoin, the
state of a thread blocked in Sleep, Join, or a
wait.
finished = t.Join(TimeSpan.FromSeconds(3));
The second wait is long enough; the thread finishes and its state is
Stopped.
$ dotnet run finished within 500 ms: False state: WaitSleepJoin finished within 3 s: True state: Stopped
C# Thread with Stopwatch
With Stopwatch we can accurately measure elapsed time. We use it
to show that threads run concurrently.
using System.Diagnostics;
var sw = Stopwatch.StartNew();
Thread[] threads = new Thread[10];
for (var i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(() =>
{
var id = Environment.CurrentManagedThreadId;
var r = Random.Shared.Next(500, 1500);
Thread.Sleep(r);
Console.WriteLine($"{id} finished in {r} ms");
});
}
foreach (var t in threads)
{
t.Start();
}
foreach (var t in threads)
{
t.Join();
}
sw.Stop();
Console.WriteLine($"elapsed: {sw.ElapsedMilliseconds} ms");
We create ten threads that sleep for a random number of milliseconds. The main thread waits until all of them finish and prints the elapsed time.
var sw = Stopwatch.StartNew();
The StartNew method creates and starts a stopwatch.
Console.WriteLine($"elapsed: {sw.ElapsedMilliseconds} ms");
The program runs about as long as its slowest thread, not as long as the sum of all sleep times.
$ dotnet run 8 finished in 729 ms 6 finished in 766 ms 4 finished in 767 ms 13 finished in 917 ms 11 finished in 930 ms 10 finished in 1108 ms 5 finished in 1185 ms 7 finished in 1255 ms 9 finished in 1359 ms 12 finished in 1472 ms elapsed: 1473 ms
Thread properties
A thread has a name, a priority, a background flag, and a state. The
IsThreadPoolThread property tells whether the thread belongs to
the thread pool.
var main = Thread.CurrentThread;
main.Name = "Main";
PrintInfo(main);
var worker = new Thread(() => PrintInfo(Thread.CurrentThread))
{
Name = "Worker",
IsBackground = true,
Priority = ThreadPriority.BelowNormal
};
Console.WriteLine($"before start: {worker.ThreadState}");
worker.Start();
worker.Join();
Console.WriteLine($"after join: {worker.ThreadState}");
ThreadPool.QueueUserWorkItem(_ => PrintInfo(Thread.CurrentThread));
Thread.Sleep(200);
void PrintInfo(Thread t)
{
Console.WriteLine($"name: {t.Name ?? "(none)"}, id: {t.ManagedThreadId}, " +
$"background: {t.IsBackground}, pool: {t.IsThreadPoolThread}, " +
$"priority: {t.Priority}");
}
The example prints information about the main thread, a dedicated worker thread, and a thread pool thread.
var worker = new Thread(() => PrintInfo(Thread.CurrentThread))
{
Name = "Worker",
IsBackground = true,
Priority = ThreadPriority.BelowNormal
};
We set the properties with an object initializer. A name helps to identify the thread in a debugger and in logs. The priority is a hint to the operating system scheduler; we should rarely need to change it.
ThreadPool.QueueUserWorkItem(_ => PrintInfo(Thread.CurrentThread)); Thread.Sleep(200);
The lambda runs on a thread pool thread. Pool threads are background threads, so we give the work item some time to complete before the program ends.
$ dotnet run name: Main, id: 1, background: False, pool: False, priority: Normal before start: Background, Unstarted name: Worker, id: 4, background: True, pool: False, priority: BelowNormal after join: Stopped name: .NET TP Worker, id: 5, background: True, pool: True, priority: Normal
Shared data and locking
Threads share the memory of the process. When several threads modify the same
variable without synchronization, updates can be lost. This is called a
race condition. The lock statement and the
Interlocked class prevent it.
const int Iterations = 1_000_000;
int unsafeCounter = 0;
int lockedCounter = 0;
int atomicCounter = 0;
var lockObj = new Lock();
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(() =>
{
for (int j = 0; j < Iterations; j++)
{
unsafeCounter++;
lock (lockObj)
{
lockedCounter++;
}
Interlocked.Increment(ref atomicCounter);
}
});
}
foreach (var t in threads) t.Start();
foreach (var t in threads) t.Join();
Console.WriteLine($"expected: {threads.Length * Iterations}");
Console.WriteLine($"unsafe: {unsafeCounter}");
Console.WriteLine($"lock: {lockedCounter}");
Console.WriteLine($"atomic: {atomicCounter}");
Four threads increment three counters a million times each.
unsafeCounter++;
The increment is not atomic. It reads the value, adds one, and writes it back. When two threads read the same value at the same time, one of the increments is lost.
lock (lockObj)
{
lockedCounter++;
}
Only one thread at a time can hold the lock, so the increments are done one by
one. The System.Threading.Lock type, available since .NET 9 and
C# 13, is a dedicated lock object; in older code, a plain
object is used.
Interlocked.Increment(ref atomicCounter);
For simple operations such as incrementing a number, the
Interlocked class provides atomic methods which are cheaper than
a lock.
The unsafe counter ends up lower than expected; the exact number differs in every run.
$ dotnet run expected: 4000000 unsafe: 3993399 lock: 4000000 atomic: 4000000
Capturing loop variables
A lambda captures variables, not values. If a thread reads a variable which the loop keeps changing, it may see a different value than intended.
for (int i = 0; i < 5; i++)
{
new Thread(() => Console.Write($"{i} ")).Start();
}
Thread.Sleep(200);
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
int copy = i;
new Thread(() => Console.Write($"{copy} ")).Start();
}
Thread.Sleep(200);
Console.WriteLine();
Both loops start five threads which print a number.
for (int i = 0; i < 5; i++)
{
new Thread(() => Console.Write($"{i} ")).Start();
}
A for loop has a single i variable shared by all
iterations. By the time the threads run, the loop has usually finished and
i is 5.
int copy = i;
new Thread(() => Console.Write($"{copy} ")).Start();
A variable declared inside the loop body is a new variable in each iteration.
Each thread prints its own number, although not necessarily in order. The
variable of a foreach loop is also fresh in each iteration.
$ dotnet run 5 5 5 5 5 1 0 2 3 4
Stopping a thread
A thread cannot be safely killed from the outside; the
Thread.Abort method is not supported in .NET Core and later.
Instead, the thread checks a CancellationToken and ends itself
when cancellation is requested.
using var cts = new CancellationTokenSource();
var worker = new Thread(() => Work(cts.Token));
worker.Start();
Thread.Sleep(1200);
Console.WriteLine("requesting cancellation");
cts.Cancel();
worker.Join();
Console.WriteLine("worker stopped");
void Work(CancellationToken token)
{
int n = 0;
while (!token.IsCancellationRequested)
{
n++;
Console.WriteLine($"working... step {n}");
Thread.Sleep(500);
}
Console.WriteLine("cleaning up");
}
The worker thread does some work in a loop until the main thread asks it to stop.
using var cts = new CancellationTokenSource();
The CancellationTokenSource creates tokens and signals
cancellation to them.
while (!token.IsCancellationRequested)
The worker checks the token in each iteration. When cancellation is requested, it leaves the loop and has a chance to clean up.
cts.Cancel(); worker.Join();
The main thread requests cancellation and waits for the worker to finish.
$ dotnet run working... step 1 working... step 2 working... step 3 requesting cancellation cleaning up worker stopped
Source
Thread class - .NET API
Managed threading best practices
In this article we have worked with threads in C#. We have started and joined threads, passed them data, used background threads, protected shared data with locks, and stopped a thread with a cancellation token. See also the C# async/await and C# Task articles.
Author
List all C# tutorials.