Reputation: 19204
Suppose you have a set of sub-tasks created like so:
var childTasks = new List<Task<ResultType>>();
for (var i = 0; i < Count; i++)
{
var childTask = new Task<ResultType>(() => { logic here });
childTasks.Add(childTask);
childTask.Start();
}
If some logical operation "A" was itself started as a Task and is running in a ThreadPool thread which we've named "A", and it calls Task.WaitAll(childTasks.Select(x => (Task)x).ToArray()); //cast Task<T> to Task and make array as required by Task.WaitAll
, is there ANY chance that ThreadPool thread "A" is returned to the pool during the WaitAll operation and used to serve one of the child tasks? In other words, is there any chance that a childTask will end up running on the same thread pool thread that the calling task was using?
Or, does WaitAll block the current thread and prevent it from returning to the pool?
Upvotes: 0
Views: 45
Reputation: 171178
A will not be returned. Your code is still on the stack. This is fundamentally so.
But task inlining can occur. Anytime you wait for a Task the TPL can directly execute that task on the current thread. This is an efficiency optimization. It is also, in my not so humble opinion, an egregious design bug. It means that waiting on any task can, in practice, execute arbitrary code at that point. This is very unpredictable.
childTask.Start()
will not do this, since it does not wait, but all the wait functions can do this. It's terrible. See https://github.com/dotnet/corefx/issues/2454
Upvotes: 1