Monday, November 14, 2022

Differences Between Task And Thread in c#

 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.


Why we need Tasks
 
It can be used whenever you want to execute something in parallel. Asynchronous implementation is easy in a task, using’ async’ and ‘await’ keywords.

Why we need a Thread
 
When the time comes when the application is required to perform few tasks at the same time.
 
Here is a beginner tutorial on Introduction to Threading in C# 


No comments:

Post a Comment