Task与Thread间的区别

本文解释了Task和Thread之间的区别,并探讨了如何使用Task来进行异步操作。Task是一种工作单元,可以执行并最终在未来某个时刻完成;而Thread则是执行方式。通常情况下,创建Task时,默认情况下会将其安排在一个线程池线程上运行。Task与Thread分离的优势在于允许框架控制工作项如何映射到可用线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过查找一些文章,得知,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.

转载于:https://www.cnblogs.com/sdikerdong/p/3603888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值