System.Threading Namespace

Namespace: System.Threading

Assembly: System.Runtime.dll (or equivalent assembly depending on .NET version)

This namespace provides types that enable you to use a variety of threading features, including creating, synchronizing, and managing threads. It offers fundamental building blocks for concurrent and parallel programming in .NET.

Classes

Name Description
Thread Represents an operating system thread that you can use to create and manage threads.
CancellationToken Propagates a notification that operations should be canceled.
Interlocked Provides atomic operations that access memory containing values that are accessed by multiple threads.
Mutex A synchronization primitive that is the equivalent of a binary semaphore in other threading systems.
Semaphore Constrains the number of threads that can access a resource or pool of resources concurrently.
SemaphoreSlim A lightweight semaphore that uses `WaitHandle` for thread synchronization.
Monitor Provides primitive synchronization methods.

Structs

Name Description
CancellationTokenSource Notifies one or more CancellationToken objects that a wait has been canceled.

Enums

Name Description
ThreadPriority Specifies the priority of a thread.
ApartmentState Specifies the COM threading model to be used for a thread.

Common Scenarios

The System.Threading namespace is central to handling concurrency in .NET applications. Key uses include:

  • Creating and managing threads: Using the Thread class to start new threads of execution.
  • Synchronization: Employing primitives like Mutex, Semaphore, and Monitor to control access to shared resources and prevent race conditions.
  • Cancellation: Utilizing CancellationToken and CancellationTokenSource to gracefully stop ongoing operations.
  • Atomic operations: Using the Interlocked class for thread-safe operations on primitive types.

For higher-level concurrency constructs, consider exploring the System.Threading.Tasks namespace, which introduces the Task Parallel Library (TPL).