Threads have been a part of .Net from v1.0, Tasks were introduced in the Task Parallel Library TPL which was released in .Net 4.0.
You can consider a Task as a more sophisticated version of a Thread. They are very easy to use and have a lot of advantages over Threads as follows:
- You can create return types to Tasks as if they are functions.
- You can the "ContinueWith" method, which will wait for the previous task and then start the execution. (Abstracting wait)
- Abstracts Locks which should be avoided as per guidlines of my company.
- You can use Task.WaitAll and pass an array of tasks so you can wait till all tasks are complete.
- You can attach task to the parent task, thus you can decide whether the parent or the child will exist first.
- You can achieve data parallelism with LINQ queries.
- You can create parallel for and foreach loops
- Very easy to handle exceptions with tasks.
- *Most important thing is if the same code is run on single core machine it will just act as a single process without any overhead of threads.
Disadvantage of tasks over threads:
- You need .Net 4.0
- Newcomers who have learned operating systems can understand threads better.
- New to the framework so not much assistance available.
Some tips:-
Always use Task.Factory.StartNew method which is semantically perfect and standard.
Take a look at Task Parallel Libray for more information
http://msdn.microsoft.com/en-us/library/dd460717.aspx