Difference between Task (System.Threading.Task) and Thread

前端 未结 5 696
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 00:45

From what I understand about the difference between Task & Thread is that task happened in the thread-pool while the thread is something that I need to managed by myself

5条回答
  •  我在风中等你
    2020-12-05 01:42

    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:

    1. You can create return types to Tasks as if they are functions.
    2. You can the "ContinueWith" method, which will wait for the previous task and then start the execution. (Abstracting wait)
    3. Abstracts Locks which should be avoided as per guidlines of my company.
    4. You can use Task.WaitAll and pass an array of tasks so you can wait till all tasks are complete.
    5. You can attach task to the parent task, thus you can decide whether the parent or the child will exist first.
    6. You can achieve data parallelism with LINQ queries.
    7. You can create parallel for and foreach loops
    8. Very easy to handle exceptions with tasks.
    9. *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:

    1. You need .Net 4.0
    2. Newcomers who have learned operating systems can understand threads better.
    3. 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

提交回复
热议问题