.NET Framework Documentation

Threading in the .NET Framework

This document provides an in-depth overview of threading capabilities within the .NET Framework. Understanding and effectively utilizing threads is crucial for developing responsive, high-performance applications. This section covers fundamental concepts, common patterns, and advanced techniques.

What is Threading?

A thread is the smallest unit of execution within a process. A process can have multiple threads, each executing concurrently and independently. This allows for parallel execution of tasks, leading to:

Core Concepts

Key concepts related to threading in .NET include:

Creating and Managing Threads

You can create and start a new thread using the Thread class:

using System;
using System.Threading;

public class ThreadExample
{
    public static void ThreadProc()
    {
        Console.WriteLine("Hello from a new thread!");
    }

    public static void Main()
    {
        Thread myThread = new Thread(ThreadProc);
        myThread.Start(); // Start the thread execution

        // Wait for the thread to finish (optional)
        myThread.Join();

        Console.WriteLine("Main thread finished.");
    }
}

Thread Synchronization

When multiple threads access shared data, synchronization is essential to avoid data corruption. The lock statement is a common way to achieve this:

public class ThreadSafeCounter
{
    private int count = 0;
    private readonly object lockObject = new object();

    public void Increment()
    {
        lock (lockObject)
        {
            count++;
            Console.WriteLine($"Count: {count}");
        }
    }
}

Other synchronization primitives offer more granular control. For instance, SemaphoreSlim can be used to limit the number of threads that can access a resource concurrently.

Thread Pool Usage

For short-lived operations, using the thread pool is more efficient than creating new threads. The ThreadPool.QueueUserWorkItem method is a common way to submit tasks to the pool:

using System;
using System.Threading;

public class ThreadPoolExample
{
    public static void TaskCallback(Object state)
    {
        Console.WriteLine($"Executing task on thread pool thread {Thread.CurrentThread.ManagedThreadId}");
    }

    public static void Main()
    {
        ThreadPool.QueueUserWorkItem(TaskCallback);
        Console.WriteLine("Task queued.");
        Thread.Sleep(1000); // Allow time for the task to execute
        Console.WriteLine("Main thread finished.");
    }
}

Advanced Topics

Tip: For new development, it is highly recommended to use the Task Parallel Library (TPL) and the async/await pattern for managing asynchronous operations, as it simplifies code, improves readability, and offers robust error handling.

Common Pitfalls

Further Reading