任务并行库 - 长时间运行任务与多个连续任务

发布于 2024-12-29 23:02:09 字数 725 浏览 8 评论 0原文

我正在研究任务并行库在我正在进行的工作项目中的使用,并希望了解长时间运行任务的优点/缺点。我还没有现实生活中的例子,只是想了解其背后的理论。

从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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最单纯的乌龟 2025-01-05 23:02:09

似乎最好尽可能避免长时间运行的任务

并不完全正确。如果您需要它,那么您将必须以某种方式创建/分配一个线程,然后带有 LongRunning 选项的任务可能是最好的选择。该标志只是通知调度程序任务可能需要一段时间,以便调度程序可以预见。它甚至可能忽略该选项。

您能否尝试将您的工作分成更小、更快的工作单元

如果可以,那就这样做。但并不是所有的事情都那么容易分开。

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. The flag simply informs the scheduler the Task might take a while so that the scheduler can anticipate. 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.

顾冷 2025-01-05 23:02:09

当您指定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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文