博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Task与Thread间的区别
阅读量:5290 次
发布时间:2019-06-14

本文共 2380 字,大约阅读时间需要 7 分钟。

通过查找一些文章,得知,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 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, is still available for existing code and for cases where you explicitly want to allocate and manage an OS thread.

According to the :

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

你可能感兴趣的文章
Java学习笔记39(转换流)
查看>>
计算一个圆的直径面积周长
查看>>
XSS攻击及防御
查看>>
7.29 DFS总结
查看>>
c++操作io常见命令
查看>>
页面JS引用添加随机参数避免页面缓存
查看>>
java的基础知识文件操作和标识符
查看>>
Tika解析word文件
查看>>
变量作用域
查看>>
.NET程序集签名
查看>>
Python操作列表
查看>>
java reflect反射---Java高级开发必须懂的
查看>>
18.5 线程的优先级
查看>>
sessionStorage/localStorage 本地存储
查看>>
SVN设置必须锁定
查看>>
Oracle 手动建库
查看>>
《架构之美》阅读笔记04
查看>>
图像状态资源的介绍~~以button按钮为例
查看>>
【转】eclipse技巧2
查看>>
Vue.js组件之同级之间的通信
查看>>