wasAsked.

What is a thread?

Routeware · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

A thread is the smallest unit of execution that the operating system schedules. A process (your running application) contains one or more threads; all threads in a process share the same memory (heap, static data), but each thread has its own stack, instruction pointer and registers. Key ideas - Main thread: every application starts with one; in UI apps it is the UI thread. - Concurrency: the OS switches between threads (context switching) so several appear to run at once; on multi-core CPUs, threads truly run in parallel. - Cost: each thread reserves stack memory (about 1 MB by default on Windows) and context switches take CPU time, so creating thousands of threads is expensive. Creating a thread directly (rare in modern code): var worker = new Thread(() => { Console.WriteLine($"Working on thread {Environment.CurrentManagedThreadId}"); }); worker.IsBackground = true; // does not keep the process alive worker.Start(); worker.Join(); // wait for completion Foreground vs background threads - Foreground threads keep the process running until they finish. - Background threads are terminated when all foreground threads end. Thread-pool threads are background threads. Thread pool - .NET maintains a pool of reusable worker threads. Tasks (Task.Run), async continuations, timers and ASP.NET Core requests run on pool threads, avoiding the cost of creating new threads. Thread lifecycle states Unstarted, Running, WaitSleepJoin (blocked on Sleep, a lock or Join), Stopped, plus suspension-related states in older APIs. Shared memory means synchronisation Because threads share data, concurrent access can cause race conditions. Protect shared state with lock, Interlocked, concurrent collections, or by keeping data immutable or thread-local ([ThreadStatic], ThreadLocal<T>, AsyncLocal<T> for async flows). Threads vs tasks vs async - Thread: a low-level OS execution unit. - Task: a higher-level unit of work, usually scheduled on the thread pool. - async/await: waits for I/O without holding a thread at all. In modern .NET, prefer tasks and async; create dedicated threads only for special long-running work with specific requirements (or use TaskCreationOptions.LongRunning).

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics