new Task 总是在 ThreadPool 线程上执行吗?

Is new Task always executed on ThreadPool thread?

这可能是一个简单而愚蠢的问题。我创建了一个这样的任务:

Task<bool> myTask = new Task<bool>(() => { Debug.WriteLine("Task fired"); return true; });
// I know I can create it with Task.Run, but this is for purpose of the sample
myTask.Start(); 

对此我有几个问题:

我已经阅读了一些文档,但没有找到具体的解释。例如 Task documentation 一般表示任务:

Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread...

回答第一点:"Beginning with the .NET Framework 4, the easiest way to use the thread pool is to use the Task Parallel Library (TPL). By default [emphasise added], parallel library types like Task and Task use thread pool threads to run tasks."

https://msdn.microsoft.com/en-us/library/0ka9477y(v=vs.110).aspx

does it always run on ThreadPool thread?

不一定。如果你看一下 Task constructor overload taking a TaskCreationOptions,你可以传递值 TaskCreationOptions.LongRunning。如果它在内部使用 TaskScheduler.Default,这将创建一个不是线程池之一的新线程。

一般情况下,建议您使用Task.Run for queuing threads on the thread-pool. If you want to pass a custom TaskScheduler, you can use the more advanced Task.Factory.StartNew,但我建议只在真正需要时才使用。

if it runs on ThreadPool is there a chance that it will be run by UI thread? And in case of havey job - can block it?

没有。 UI 线程不是 ThreadPool 使用的池的一部分。

in case of large number of tasks, can few be assigned to one thread (queued) and then run one after another? Or every task has its own thread?

这是特定于正在使用的 TaskScheduler 的实现。如果我们查看 ThreadPoolTaskScheduler(这是默认值,以防未传递自定义值),线程池从恒定数量的线程开始,并根据需要进行扩展。不保证每个委托将在不同的线程上执行。但是,您可以创建一个自定义 TaskScheduler,您可以在其中控制执行计划任务的机制。