Reputation: 21251
I understand that the TPL does not necessarily create a new thread for every task in a parallel set, but does it always create at least one? eg:
private void MyFunc()
{
Task.Factory.StartNew(() =>
{
//do something that takes a while
});
DoSomethingTimely(); //is this line guaranteed to be hit immediately?
}
EDIT: To clarify: Yes, I mean is it guaranteed that the thread executing MyFunc()
is not going to be used to execute //do something that takes a while
.
Upvotes: 1
Views: 2581
Reputation: 239664
That's up to whatever the current default TaskScheduler
is. You can just about envisage someone doing something horrific like implementing a SynchronousTaskScheduler
that executes the task body during QueueTask
and sets it to complete before returning.
Assuming you're not letting someone else muck about with your task schedulers, you shouldn't have to worry about it.
Upvotes: 7
Reputation: 182761
Your main question and the question in your code are completely different questions. But the answers to the two questions are:
1) No, there's no guarantee a thread will be started. What is created and started is a task. Ultimately, some thread will have to execute that task, but whether one will be created is unspecified. An existing thread could be re-used.
2) It depends what you mean by "immediately". Strictly speaking, there is no timeliness guarantee. But you have told the system to execute that task, and it will at least start it as soon as it finishes everything it considers more important. Strict fairness or timeliness is not guaranteed.
Upvotes: 2
Reputation: 65274
In short: Yes, this is guranteed.
Longer: If StartNew()
does not create a new thread, it will reuse another: Either by it being free, or by queueing.
Upvotes: 1
Reputation: 14734
Yes, it will hit very shortly after dispatching the task to run.
No, it will not create a new thread, but claim one. When they say it doesn't always create a new thread, they are referring to the fact that it re-uses threads from a thread pool.
The size of the pool is based on the number of CPU cores detected. But it will always contain at least 1 thread. ;)
Upvotes: 1
Reputation: 39013
DoSomethingTimely will get called very quickly, but what does that have to do with creating a new thread, or adding the task to a queue?
Upvotes: 0
Reputation: 1500514
It depends on what you mean by "immediately" but I think it's reasonable to assume that the TPL isn't going to hijack your currently executing thread to synchronously run the code in your task, if that's what you mean. At least not with the normal scheduler... you could probably write your own scheduler which does do so, but you can normally assume that StartNew
will schedule the task rather than just running it inline.
Upvotes: 5