简体   繁体   中英

Is new Task always executed on ThreadPool thread?

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...

does it always run on ThreadPool thread?

Not necessarily. If you take a look at the Task constructor overload taking a TaskCreationOptions , you can pass the value TaskCreationOptions.LongRunning . If internally it uses TaskScheduler.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 custom TaskScheduler , you can use the more advanced Task.Factory.StartNew , but I'd recommend only using it when really needed.

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?

No. The UI thread isn't part of the pool used by the 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?

That is implementation specific to the TaskScheduler being used. If we look at the ThreadPoolTaskScheduler (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 custom TaskScheduler , 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM