平行是否与调用多个任务相同。

发布于 2025-02-13 14:01:59 字数 261 浏览 1 评论 0原文

task.run:排队在threadpool上运行的指定工作并返回任务或task< tresult>为此工作。

Parallel.Invoke:可能并行执行每个提供的操作。

有效地,他们从线程池中旋转了一个新线程。那么Parallel.Invoke与调用多个task.run s相同吗?

Task.Run: Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.

Parallel.Invoke: Executes each of the provided actions, possibly in parallel.

Effectively they spin up a new thread from the thread pool. So is Parallel.Invoke same as calling multiple Task.Runs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

失退 2025-02-20 14:01:59

因此,您想比较这两种技术:

Parallel.Invoke(source.Select(source => () => ProcessItem(source)).ToArray());
Task.WaitAll(source.Select(source => Task.Run(() => ProcessItem(source))).ToArray());

有一个相似之处和两个区别。相似之处是在两种情况下
Parallel.Invoke/task.waitall返回之前,将调用和完成所有操作。某些动作是否失败都没关系。不支持失败策略。

这两个区别是:

  1. Parallel.Invoke 将当前线程用作工作线程之一。相反,task.waitall+task.run专门使用threadpool threads。当工作线程正常工作时,当前线程无需任何操作。

  2. 可以使用特定的maxDegreeofParallelismtaskschedulerconcellation> concellationToken paralleloptions )。 task.run不可能。 task.factory.startnew可能是可能的,但是相对繁琐。

So you want to compare these two techniques:

Parallel.Invoke(source.Select(source => () => ProcessItem(source)).ToArray());
Task.WaitAll(source.Select(source => Task.Run(() => ProcessItem(source))).ToArray());

There is one similarity and two differences. The similarity is that in both cases
all actions will be invoked and completed before the Parallel.Invoke/Task.WaitAll returns. It doesn't matter if some of the actions fail. There is no support for a fail-fast strategy.

The two differences are:

  1. The Parallel.Invoke uses the current thread as one of the worker threads. On the contrary the Task.WaitAll+Task.Run uses exclusively ThreadPool threads. While the worker threads are working, the current thread is blocked doing nothing.

  2. The Parallel.Invoke can be configured with a specific MaxDegreeOfParallelism, TaskScheduler and CancellationToken (ParallelOptions). This is not possible with the Task.Run. It is possible with the Task.Factory.StartNew, but comparatively it's quite cumbersome.

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