简体   繁体   English

任务并行库 - LongRunning任务与多个Continuations

[英]Task Parallel Library - LongRunning task vs Multiple Continuations

I'm researching the usage of the Task Parallel Library for a work project I'm doing and want to understand the advantages/disadvantages of long running tasks. 我正在研究任务并行库的用法,用于我正在做的工作项目,并希望了解长时间运行任务的优点/缺点。 I haven't got a real-life example yet, just want to understand the theory behind this. 我还没有现实生活中的例子,只想了解这背后的理论。

From what the MSDN pages say about task schedulers and this SO question , it would seem as though it is best to avoid long-running tasks as much as possible so that you are not creating threads outside of the ThreadPool. 从MSDN页面所说的任务调度程序和这个SO问题来看,似乎最好尽可能避免长时间运行的任务,这样你就不会在ThreadPool之外创建线程。 But say you did have a task which was going to take a long time to complete, instead of this: 但是说你确实有一项任务需要很长时间才能完成,而不是这样:

Task.Factory.StartNew(() => DoTimeConsumingWork(), TaskCreationOptions.LongRunning)

Could you try and split up your work into smaller, quicker units of work and use task continuations, like this: 您是否可以尝试将您的工作分成更小,更快的工作单元并使用任务延续,如下所示:

Task.Factory
    .StartNew(() => DoWorkPart1())
    .ContinueWith(t => DoWorkPart2())
    .ContinueWith(t => DoWorkPart3())
    //...etc

Would this approach be any more beneficial or is it overkill for what it is trying to achieve? 这种方法是否会更有益,或者它试图实现的目标是否过度?

it would seem as though it is best to avoid long-running tasks as much as possible 似乎最好尽可能避免长时间运行的任务

Not entirely correct. 不完全正确。 If you need it then you will have to make/allocate a thread somehow and then the Task with LongRunning option is probably the best choice. 如果你需要它,那么你将不得不以某种方式制作/分配一个线程,然后使用LongRunning选项的任务可能是最好的选择。 The flag simply informs the scheduler the Task might take a while so that the scheduler can anticipate. 该标志只是通知调度程序,Task可能需要一段时间,以便调度程序可以预期。 It might even ignore the option. 它甚至可能会忽略该选项。

Could you try and split up your work into smaller, quicker units of work a 你能尝试将你的工作分成更小,更快的工作单位吗?

If you can, then do it. 如果可以,那就去做吧。 But not al taks are so easily separated. 但是,并非如此容易分开。

When you specify TaskCreationOptions.LongRunning mostly it assigns a dedicated thread from outside of thread pool. 当您指定TaskCreationOptions.LongRunning它主要从线程池外部分配一个专用线程。

I would suggest simply go for BackgroundWorker class which makes sure your long running task will be ran on a separate dedicated thread instead of a thread from thread pool 我建议只使用BackgroundWorker类,它确保您的长时间运行任务将在一个单独的专用线程上运行,而不是从线程池中运行一个线程

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM