wasAsked.

Multithreading

EPAM · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

Multithreading means running multiple threads within one process so that work can happen concurrently — on multiple CPU cores in parallel, or interleaved on fewer cores. Why use it - Use multiple CPU cores for CPU-heavy work (image processing, calculations). - Keep applications responsive (UI thread free while work runs elsewhere). - Handle many independent operations concurrently. Ways to do it in .NET (from low-level to high-level) - Thread class: full control, but expensive to create; rarely used directly now. - ThreadPool: reuses threads; the runtime manages it. - Task Parallel Library: Task.Run(() => Compute()) schedules work on the thread pool. - Parallel class and PLINQ: Parallel.For, Parallel.ForEach, Parallel.ForEachAsync (with MaxDegreeOfParallelism), and AsParallel() for data parallelism. - async/await: for I/O-bound concurrency without blocking threads (not multithreading by itself, but often confused with it). - Channels and BackgroundService: producer/consumer pipelines in server applications. Example — process files in parallel with limited concurrency: await Parallel.ForEachAsync(files, new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = ct }, async (file, token) => await ProcessAsync(file, token)); Challenges and how to handle them - Race conditions: two threads modifying shared data. Use lock, Interlocked, concurrent collections (ConcurrentDictionary, ConcurrentQueue) or immutable data. - Deadlocks: threads waiting on each other's locks. Acquire locks in a consistent order, keep critical sections short, use timeouts. - Thread starvation: blocking pool threads with .Result or Thread.Sleep. Use async APIs. - Visibility issues: use proper synchronisation (lock, volatile, Interlocked) so threads see updated values. - Context switching overhead: more threads than cores does not mean faster for CPU work. Synchronisation primitives: lock (or System.Threading.Lock in .NET 9+), Monitor, Mutex (cross-process), SemaphoreSlim (limit concurrency, async-friendly), ReaderWriterLockSlim, ManualResetEventSlim, Barrier, CountdownEvent. In web APIs, the server is already multithreaded (each request runs on pool threads), so the main concern is thread-safe shared state and async I/O rather than creating threads manually.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics