Task與Thread間的區別


通過查找一些文章,得知,Task與Thread不可比。Task是為了利用多CPU多核的機制而將一個大任務不斷分解成小任務,這些任務具體由哪一個線程或當前線程執行由OS來決定。如果你想自己控制由哪一個Thread執行,要么自己定議task的scheduling, 要么自己來創建Thread來執行代碼。

A "Task" is a piece of work that will execute, and complete at some point in the future.

A "Thread" is how something gets executed.

Typically, when you create a Task, by default (ie: using Task.Factory.StartNew), the Task will get Scheduled to run upon a ThreadPool thread at some point.  However, this is not always true.

The advantage of making this separation is that you are allowing the framework (or yourself, if you use a custom TaskScheduler) to control how your work gets mapped onto available threads.  Typically, you'll have many more work items than threads - you may have one million items to process, but only 8 cores in your system.  In a situation like this, it's much more efficient to use a fixed number of threads, and have each thread process multiple items of work.  By separating "Task" from "Thread", you're breaking this coupling of work==thread.

In general, I would recommend using Task instead of creating your own threads.  This is a much nicer, more powerful, and flexible model to use for development, especially as it allows you to handle exceptions in a very clean manner, allows nice things like continuations to be generated, etc.

 

 

So it appears that a Task is the preferred means of coding an asynchronous operation, as much of the work is taken care of by the framework. But on the other hand, Thread is still available for existing code and for cases where you explicitly want to allocate and manage an OS thread.

According to the MSDN reference documentation:

The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces in the .NET Framework version 4. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM