C# Multithreading – Difference Between Task and Thread in .NET 4.0

.net-4.0c++multithreading

Today I was digging with TPL and found a new class Task.Now I just wanted to know that what is diffrence between task and Thread,and which one is better?

Best Answer

what is diffrence between a task and a thread?

Suppose you are running a book delivery company. You have four cars and four drivers. A car is a thread, a driver is a processor, and a book delivery is a task. The problem you face is how to efficiently schedule the drivers and cars so that the tasks get done as quickly as possible.

Where things get weird is when there are more cars (threads) than drivers (processors). What happens then is halfway through a trip the driver parks one car (suspends the thread) and gets into a different car (switches context), drives that one around for a while performing tasks, and then eventually comes back to the first car. Obviously that is not as efficient as one driver staying in one car.

The idea of task-based parallism is to break up the work into small tasks that can produce results in the future, and then efficiently allocate exactly as many threads as there are processors so that you don't waste time context switching. In practice, it usually does not work out that nicely, but that's the idea.

which one is better, task or thread?

The question cannot be answered because it doesn't make any sense. Which is better, a book to deliver to a customer, or a car to deliver it in? A car is a device that can be used to deliver a book; those two things are not things you can sensibly describe as "better" or "worse" than the other. It's like asking "which is better, a hole or a drill?"

Related Question