线程可以开始通过任务并行库充当前台线程?线程、前台、任务

2023-09-04 11:48:23 作者:乱世巨星

MSDN文档表明由TPL开始线程将享受更好的调度。然而,由于线程是基于线程池,它们将被实施为后台线程

MSDN documentation indicates that threads started by the TPL will enjoy better scheduling. However, since the threads are based upon ThreadPool, they will be implemented as background threads.

现在,有一些任务,我想在平行于中进行,但它必须是,这些任务中进行,直到完成。

Now, there are some tasks I would like to be carried out in parallel, but it is imperative that these tasks be carried out until completion.

那么,如何创建这样的任务基本上是前台线程,但仍享有由TPL提供的增强调度?

So, how do I create such tasks that are essentially foreground threads, but still enjoy the enhanced scheduling provided by the TPL?

推荐答案

在TPL并没有真正给你的线程,它可以让你创建任务。任务可以在不同的线程中执行,因此任务!=线程。

The TPL does not really give you Threads, it lets you create Tasks. Tasks can be executed on different threads, so Task != Thread.

由于与普通的线程池,它不会是一个好主意,改变任何线程性能。

As with the plain Threadpool, it would not be a good idea to change any Thread-properties.

但是,你的问题可以很容易地通过等待从主线程中未完成的任务解决。通常你想捕获并处理它们的异常了。

But you problem could be easily solved by Waiting for any outstanding tasks from the main thread. You usually want to catch and handle their exceptions too.