System.Threading

Namespace: System.Threading

Provides types that enable working with threads and synchronization primitives.

namespace System.Threading

Classes

Classes

  • Thread Represents an operating system thread.
  • ThreadPool Provides a pool of reusable threads for multithreaded operations.
  • CancellationTokenSource Propagates a notification that operations should be canceled.
  • Interlocked Provides atomic operations that ensure thread safety without using locking.
  • Monitor Provides basic synchronization services.
  • Mutex Represents a thread-synchronizing object that can be held by a single thread.
  • Semaphore Constrains the number of threads that can access a resource or pool of resources concurrently.
  • SemaphoreSlim Represents a Semaphore that uses an efficient, low-level synchronization primitive.
  • CountdownEvent Notifies one or more threads that an event has occurred.
  • Barrier Represents a synchronization primitive that synchronizes threads.

Structs

Structs

  • CancellationToken Notifies code that an operation should be cancelled.
  • Lazy<T> Represents an object whose initialization is deferred until the first use.

Enums

Enums

Delegates

Delegates

  • ParameterizedThreadStart Represents a method to be executed by a new thread that takes a single object parameter.
  • ThreadStart Represents a method to be executed by a new thread.

Thread Class

Represents an operating system thread.

Methods

public void Start()

Starts the execution of the thread.

public void Start(object parameter)

Starts the execution of the thread with a parameter.

parameter
An object containing information to be used by the method the thread executes.
public void Abort()

ObsoleteAttribute. Attempts to abort the thread. This method is not recommended for use, as it can leave an application in an unstable state.

public void Join()

Waits for the thread to terminate.

public static Thread CurrentThread { get; }

Gets the currently executing thread.

ThreadPool Class

Provides a pool of reusable threads for multithreaded operations.

Methods

public static bool QueueUserWorkItem(WaitCallback callBack)

Adds a method to the queue that will be executed by a thread pool thread.

callBack
A delegate of type WaitCallback that represents the method to execute.
public static bool QueueUserWorkItem(WaitCallback callBack, object state)

Adds a method to the queue that will be executed by a thread pool thread.

callBack
A delegate of type WaitCallback that represents the method to execute.
state
An object containing information to be used by the method.
public static void SetMaxThreads(int value)

Sets the maximum number of concurrent threads that can be in the pool.

public static void SetMinThreads(int value)

Sets the minimum number of threads that the thread pool will maintain.

CancellationTokenSource Class

Propagates a notification that operations should be canceled.

Methods

public CancellationTokenSource()

Initializes a new instance of the CancellationTokenSource class.

public void Cancel()

Signals the cancellation request to threads that are listening to this CancellationTokenSource instance.

public void CancelAfter(int millisecondsDelay)

Signals the cancellation request after the specified delay.

millisecondsDelay
The delay, in milliseconds, after which the token will be canceled.
public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2)

Creates a CancellationTokenSource that will be linked to the specified tokens.

CancellationToken Struct

Notifies code that an operation should be cancelled.

Properties

public bool CanBeCanceled { get; }

Gets whether this CancellationTokenSource instance supports cancellation.

public bool IsCancellationRequested { get; }

Gets whether cancellation has been requested for this token.

public static CancellationToken None { get; }

Gets an instance of CancellationToken that is not linked to any CancellationTokenSource and is not canceled.

Methods

public void ThrowIfCancellationRequested()

Throws an OperationCanceledException if cancellation has been requested.

Interlocked Class

Provides atomic operations that ensure thread safety without using locking.

Methods

public static int Increment(ref int location)

Atomically increments the specified variable by one.

public static long Increment(ref long location)

Atomically increments the specified variable by one.

public static int Decrement(ref int location)

Atomically decrements the specified variable by one.

public static long Decrement(ref long location)

Atomically decrements the specified variable by one.

public static int Exchange(ref int location1, int value)

Atomically exchanges the value at location1 with value and returns the original value at location1.

public static T Exchange<T>(ref T location1, T value) where T : class

Atomically exchanges the value at location1 with value and returns the original value at location1.

public static int CompareExchange(ref int location1, int value, int comparand)

Atomically compares two integers and, if they are equal, replaces the second integer with the third integer and returns the original value of the second integer.

public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class

Atomically compares two object references and, if they are equal, replaces the second object reference with the third object reference and returns the original value of the second object reference.

Monitor Class

Provides basic synchronization services.

Methods

public static void Enter(object obj)

Enters a critical section. If the specified object is already locked by another thread, the current thread is blocked until it can enter the critical section.

public static void Exit(object obj)

Exits a critical section. The Monitor will be released by the calling thread.

public static bool TryEnter(object obj)

Enters a critical section. If the specified object is already locked by another thread, the current thread attempts to enter the critical section and returns true if the lock is acquired and false otherwise.

public static bool TryEnter(object obj, int timeout)

Enters a critical section. If the specified object is already locked by another thread, the current thread waits for the specified time. If the lock is acquired within the specified time, returns true; otherwise, returns false.

Mutex Class

Represents a thread-synchronizing object that can be held by a single thread.

Methods

public Mutex()

Initializes a new, unnamed, mutually exclusive wait event.

public Mutex(bool initiallyOwned)

Initializes a new instance of the Mutex class with a Boolean value indicating whether the calling thread has ownership of the mutex.

public void WaitOne()

Waits until the calling thread can enter the mutex.

public bool WaitOne(TimeSpan timeout)

Waits until the calling thread can enter the mutex, using a TimeSpan to define the timeout.

public void ReleaseMutex()

Releases the mutex.

Semaphore Class

Constrains the number of threads that can access a resource or pool of resources concurrently.

Methods

public Semaphore(int initialCount, int maximumCount)

Initializes a new instance of the Semaphore class with the specified initial and maximum counts.

public int WaitOne()

Decrements the current count of the semaphore, blocking until the count is positive or the thread is canceled. If successful, decrements the count.

public bool WaitOne(TimeSpan timeout)

Waits until the calling thread can enter the semaphore, using a TimeSpan to define the timeout. If successful, decrements the count.

public void Release()

Increments the count of the semaphore, releasing a thread that is waiting for the semaphore.

public int Release(int releaseCount)

Increments the count of the semaphore by the specified amount, releasing that many threads.

SemaphoreSlim Class

Represents a Semaphore that uses an efficient, low-level synchronization primitive.

Methods

public SemaphoreSlim(int initialCount)

Initializes a new instance of the SemaphoreSlim class.

public SemaphoreSlim(int initialCount, int maxCount)

Initializes a new instance of the SemaphoreSlim class with the specified initial and maximum counts.

public bool Wait(TimeSpan timeout)

Waits until a thread can enter the SemaphoreSlim. If the current thread is not the last thread to exit the semaphore, blocks until the semaphore is released.

public void Wait()

Waits until a thread can enter the SemaphoreSlim.

public bool WaitAsync().AsTask()

Asynchronously waits until a thread can enter the SemaphoreSlim.

public bool Release()

Releases the SemaphoreSlim.

public int Release(int releaseCount)

Releases the SemaphoreSlim by the specified amount.

CountdownEvent Class

Notifies one or more threads that an event has occurred.

Methods

public CountdownEvent(int initialCount)

Initializes a new instance of the CountdownEvent class with the specified initial count.

public bool Signal()

Signals that one signal has been received. Returns true if the event was signaled and the count reached zero; otherwise, false.

public void Wait()

Blocks until the current CountdownEvent count reaches zero.

public bool Wait(TimeSpan timeout)

Blocks until the current CountdownEvent count reaches zero, using a TimeSpan to define the timeout.

Barrier Class

Represents a synchronization primitive that synchronizes threads.

Methods

public Barrier(int participantCount)

Initializes a new instance of the Barrier class with the specified number of participants.

public void SignalAndWait()

Signals that a participant has reached the barrier and blocks until all participants have reached the barrier.

public bool SignalAndWait(TimeSpan timeout)

Signals that a participant has reached the barrier and blocks until all participants have reached the barrier or the specified timeout occurs.

ThreadState Enum

Specifies the execution state of a thread.

Members

Running

Stopped

Suspended

WaitSleepJoin

Aborted

ThreadPriority Enum

Specifies the priority of a thread.

Members

Lowest

BelowNormal

Normal

AboveNormal

Highest

ThreadStart Delegate

Represents a method to be executed by a new thread.

Signature

delegate void ThreadStart();

ParameterizedThreadStart Delegate

Represents a method to be executed by a new thread that takes a single object parameter.

Signature

delegate void ParameterizedThreadStart(object obj);