Skip to content

Multithreading

Multithreading allows your application to perform multiple operations simultaneously. It's essential for building responsive applications that can handle concurrent operations efficiently.

Creating Threads

Threads are the basic units of program execution. Creating and managing threads allows you to run multiple operations concurrently.

csharp
// Basic thread creation
Thread thread = new Thread(() => 
{
    Console.WriteLine("Thread is running");
});
thread.Start();

// Parameterized thread
Thread paramThread = new Thread(param => 
{
    Console.WriteLine($"Received: {param}");
});
paramThread.Start("Hello");

Thread Synchronization

Thread synchronization prevents multiple threads from accessing shared resources simultaneously, avoiding race conditions and ensuring data consistency.

csharp
private static object _lock = new object();

public void SafeMethod()
{
    lock (_lock)
    {
        // Thread-safe code here
    }
}

Thread Pool

The thread pool manages a collection of reusable threads, optimizing system resources and improving application performance.

csharp
ThreadPool.QueueUserWorkItem(state => 
{
    Console.WriteLine("Work item executed");
});

Parallel Processing

Parallel processing enables efficient execution of tasks across multiple processors or cores, maximizing CPU utilization.

csharp
// Parallel.For
Parallel.For(0, 10, i => 
{
    Console.WriteLine($"Processing {i}");
});

// Parallel.ForEach
var items = Enumerable.Range(0, 100);
Parallel.ForEach(items, item => 
{
    ProcessItem(item);
});