Task Vs Thread differences in C#
- In computer science, a Task is a future or a promise.
- A Thread is a way of fulfilling that promise.
You can use Task to specify what you want to do then attach that Task with a Thread. In .NET 4.0 terms, a Task represents an asynchronous operation . Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads .
What is a Task?
A task is something you want done. It is a set of program instructions that are loaded in memory . When program instruction is loaded into memory people do call as process or task. Task and Process are synonyms nowadays. A task will by default use the Threadpool , which saves resources as creating threads can be expensive. The Task can tell you if the work is completed and if the operation returns a result. Also, you can see a Task as a higher level abstraction upon threads.
What is a Thread?
A thread is a basic unit of CPU utilization , consisting of a program counter, a stack, and a set of registers. Thread has its own program area and memory area . A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler. Threads are not a .NET construct, they are built into your operating system . The thread class from .NET is just a way to create and manage threads. Threads can themselves split into two or more simultaneously running tasks .
Differences Between Task And Thread
- Task is more abstract then threads. It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance.
- The task can return a result. There is no direct mechanism to return the result from a thread.
- Task supports cancellation through the use of cancellation tokens. But Thread doesn't.
- A task can have multiple processes happening at the same time. Threads can only have one task running at a time.
- You can attach task to the parent task, thus you can decide whether the parent or the child will exist first.
- While using thread if we get the exception in the long running method it is not possible to catch the exception in the parent function but the same can be easily caught if we are using tasks.
- You can easily build chains of tasks. You can specify when a task should start after the previous task and you can specify if there should be a synchronization context switch. That gives you the great opportunity to run a long running task in background and after that a UI refreshing task on the UI thread.
- A task is by default a background task. You cannot have a foreground task. On the other hand a thread can be background or foreground.
- The default TaskScheduler will use thread pooling, so some Tasks may not start until other pending Tasks have completed. If you use Thread directly, every use will start a new Thread.