Sobes.tech
Middle

What is the difference between threads and tasks in C#?

sobes.tech AI

Answer from AI

Threads are a low-level abstraction of the operating system for executing code in parallel. Tasks are a higher-level concept in .NET, based on the thread pool, simplifying asynchronous and parallel programming.

Main differences:

  • Level of abstraction: Thread works directly with OS threads. Task is an abstraction managed by a scheduler (usually ThreadPool).
  • Management: Managing threads manually (creation, start, stop) can be complex. Task is managed by the scheduler, making it easier to use.
  • Resources: Creating a new Thread requires more system resources than using a Task from the thread pool.
  • Return values and exceptions: Task has built-in mechanisms for obtaining return values (Task<TResult>) and handling unhandled exceptions. For Thread, this requires manual implementation.
  • Asynchrony: Task is closely integrated with the keywords async and await, which greatly simplifies writing asynchronous code. Thread requires manual use of callbacks or other mechanisms for asynchrony.
  • Cancellation: Cancellation of a Task is supported via CancellationToken. Cancellation of a Thread requires manual implementation of interruption mechanisms.

Example of creation and waiting:

// Using Task
async Task MyTaskAsync()
{
    await Task.Delay(100);
    Console.WriteLine("Task finished");
}

// Starting and waiting for Task
Task t = MyTaskAsync();
await t;

// Using Thread (a lower-level approach)
Thread myThread = new Thread(() =>
{
    Thread.Sleep(100);
    Console.WriteLine("Thread finished");
});

// Starting Thread
myThread.Start();

// Waiting for Thread to complete (blocking call)
myThread.Join();