简体   繁体   English

是否存在不应使用任务的情况?

[英]Are there any scenario where Tasks should not be used?

I am reading about Tasks been preferred way of doing async programming with 4.0. 我正在阅读有关使用4.0进行异步编程的首选方法。 I am just wondering if there are any use cases where use of Tasks should not be preferred over normal c# threads? 我只是想知道是否有任何用例不应该优先使用任务而不是普通的c#线程?

Since Task s use the underlying ThreadPool (unless marked as long running), it's a bad idea to use them whenever using a ThreadPool is not advised eg 由于Task使用底层的ThreadPool (除非标记为长时间运行),因此在不建议使用ThreadPool时使用它们是个坏主意,例如

  • long I/O operations that clog the task queue and prevent other tasks from being executed. 阻塞任务队列并阻止执行其他任务的长I / O操作。
  • doing operations that require thread identity such as setting affinity. 执行需要线程标识的操作,例如设置关联。

This is gone into detail over here: Should I notice a difference in using Task vs Threads in .Net 4.0? 这里详细介绍: 我是否应该注意到.Net 4.0中使用Task vs Threads的区别?

This biggest difference is that the TaskFactory uses thread pooling, so if you have a lot of tasks they may not start immediately. 最大的区别是TaskFactory使用线程池,所以如果你有很多任务,它们可能无法立即启动。 They have to wait for a free thread to run. 他们必须等待一个免费的线程运行。 In most cases this is acceptable.. 大多数情况下这是可以接受的..

Threads will run instantly as soon as .Start() is called, hardware permitting. 一旦调用.Start(),硬件允许,线程就会立即运行。

Assuming Thread pooling is okay, Tasks offer many benefits including cancellation, ContinueWith, OnSuccess, OnError, Exception aggregation, and WaitAll to name a few off the top of my head. 假设线程池是可以的,Tasks提供了很多好处,包括cancel,ContinueWith,OnSuccess,OnError,Exception聚合和WaitAll等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TcpClient是否应用于这种情况? - Should TcpClient be used for this scenario? async不应该用于高CPU任务吗? - Is it true that async should not be used for high-CPU tasks? 可以在.NET应用程序中等待1000个任务的集合吗? 或者应该使用批处理? - Is it ok to await a collection of 1000 tasks in a .NET app? Or should batching be used? 什么是谓词委托,应该在哪里使用它? - What is a Predicate Delegate and where should it be used? Task.ContinueWith(...,TaskScheduler.FromCurrentSynchronizationContext())在UI线程上运行的任何场景? - Any scenario where Task.ContinueWith(…, TaskScheduler.FromCurrentSynchronizationContext()) would *not* run on the UI thread? 是否有任何情况下Rope数据结构比字符串生成器更有效 - Is there any scenario where the Rope data structure is more efficient than a string builder 我应该使用懒惰吗 <T> 在可能不使用类的控制器中? - Should I use Lazy<T> in a controller where a class may not be used? 保存的文件模板中使用的文件应放在何处? - Where should files used in a saved file template be placed? 我是否应该将变量声明为尽可能接近将使用它们的 scope? - Should I declare variables as close as possible to the scope where they will be used? 我应该在哪里保存用于xml签名验证的公钥? - Where should I save the public key used for xml signature verification?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM