任务并行库 - 长时间运行任务与多个连续任务
我正在研究任务并行库在我正在进行的工作项目中的使用,并希望了解长时间运行任务的优点/缺点。我还没有现实生活中的例子,只是想了解其背后的理论。
从MSDN页面关于任务调度程序和这个SO问题,似乎最好尽可能避免长时间运行的任务尽可能避免在线程池之外创建线程。但是,假设您确实有一项需要很长时间才能完成的任务,而不是这样:
Task.Factory.StartNew(() => DoTimeConsumingWork(), TaskCreationOptions.LongRunning)
您能否尝试将您的工作拆分为更小、更快的工作单元并使用任务延续,如下所示:
Task.Factory
.StartNew(() => DoWorkPart1())
.ContinueWith(t => DoWorkPart2())
.ContinueWith(t => DoWorkPart3())
//...etc
这种方法可以吗?更有益还是对于它想要实现的目标来说是矫枉过正?
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. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
并不完全正确。如果您需要它,那么您将必须以某种方式创建/分配一个线程,然后带有 LongRunning 选项的任务可能是最好的选择。该标志只是通知调度程序任务可能需要一段时间,以便调度程序可以预见。它甚至可能忽略该选项。
如果可以,那就这样做。但并不是所有的事情都那么容易分开。
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. The flag simply informs the scheduler the Task might take a while so that the scheduler can anticipate. It might even ignore the option.
If you can, then do it. But not al taks are so easily separated.
当您指定TaskCreationOptions.LongRunning时,它通常会从线程池外部分配一个专用线程。
我建议简单地使用BackgroundWorker类,它可以确保您的长时间运行的任务将在单独的专用线程上运行,而不是在线程池中的线程上运行
When you specify
TaskCreationOptions.LongRunning
mostly it assigns a dedicated thread from outside of thread pool.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