This is probably an easy and dumb question. I create a task like this:
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();
and I've few questions about this:
- Does it always run on ThreadPool thread?
- 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?
- 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?
I've read some documentation, but I failed to find concrete explanation. For example Task documentation says generally about Tasks:
Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread...
Not necessarily. If you take a look at the
Task
constructor overload taking aTaskCreationOptions
, you can pass the valueTaskCreationOptions.LongRunning
. If internally it usesTaskScheduler.Default
, this will create a new thread which isn't one of the threadpool's.Generally, it is recommended that you use
Task.Run
for queuing threads on the thread-pool. If you want to pass a customTaskScheduler
, you can use the more advancedTask.Factory.StartNew
, but I'd recommend only using it when really needed.No. The UI thread isn't part of the pool used by the ThreadPool.
That is implementation specific to the
TaskScheduler
being used. If we look at theThreadPoolTaskScheduler
(which is the default in case no custom one is passed) the threadpool starts with a constant amount of threads, and scales as it needs. It is not guaranteed that each delegate will execute on a different thread. You can, however, create a customTaskScheduler
, where you control the mechanism of scheduling tasks for exectuion.To answer the first point: "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