System.Threading Namespace
Provides classes and interfaces that enable highly scalable and efficient multithreaded applications.
namespace System.Threading;
The System.Threading namespace is fundamental for developing concurrent applications in .NET. It offers a comprehensive set of tools for managing threads, synchronizing access to shared resources, and coordinating the execution of multiple tasks.
Classes
Thread
public sealed class Thread : CriticalFinalizerObject, _Thread
Represents an execution thread. Threads are lightweight processes that allow your application to run multiple operations concurrently.
Example:
using System;
using System.Threading;
public class Example
{
public static void ThreadProc()
{
Console.WriteLine("Hello from the worker thread!");
}
public static void Main()
{
Thread workerThread = new Thread(ThreadProc);
workerThread.Start();
Console.WriteLine("Hello from the main thread!");
workerThread.Join(); // Wait for the worker thread to finish
}
}
ThreadPool
public static class ThreadPool
Provides a pool of reusable threads that you can use to execute methods asynchronously. Using the thread pool can improve application performance by reducing the overhead of creating and destroying threads.
Example:
using System;
using System.Threading;
public class Example
{
public static void TaskCallback(Object state)
{
Console.WriteLine("Executing task on ThreadPool thread.");
}
public static void Main()
{
ThreadPool.QueueUserWorkItem(TaskCallback);
Console.WriteLine("Task queued. Main thread continues.");
Thread.Sleep(1000); // Give the thread pool thread time to execute
}
}
CancellationTokenSource
public sealed class CancellationTokenSource : IDisposable
Represents the mechanism by which an asynchronous operation is canceled.
Mutex
public sealed class Mutex : WaitHandle, IDisposable
A thread-synchronizing object that can be owned by only one thread at a time. When a thread acquires a mutex, it becomes the owner, and other threads attempting to acquire the mutex will block until the owning thread releases it.
Semaphore
public class Semaphore : WaitHandle, IDisposable
A synchronization primitive that restricts the number of threads that can access a resource or pool of resources concurrently.
Monitor
public static class Monitor
Provides static methods for synchronizing the execution of threads. These methods are used to enter and exit critical sections of code that must be executed by only one thread at a time.
Interfaces
IAsyncResult
public interface IAsyncResult
Represents the status of an asynchronous operation.
CancellationToken
public struct CancellationToken
Notifies lower-chop operations that they should be canceled.
Common Scenarios
When working with multithreading, you'll often encounter scenarios such as:
- Background Operations: Performing long-running tasks without blocking the UI thread.
- Resource Sharing: Safely accessing and modifying shared data structures from multiple threads.
- Task Parallelism: Breaking down a computation into smaller pieces that can be executed in parallel.
- Cancellation: Providing a mechanism to stop ongoing operations when they are no longer needed.
Using `Task` for simpler asynchronous operations (introduced in .NET Framework 4.0 and fully supported in .NET Core):
using System;
using System.Threading.Tasks;
public class Example
{
public static async Task DoWorkAsync()
{
Console.WriteLine("Starting async work...");
await Task.Delay(1000); // Simulate work
Console.WriteLine("Async work finished.");
}
public static async Task Main()
{
Console.WriteLine("Main method started.");
await DoWorkAsync();
Console.WriteLine("Main method finished.");
}
}