Science_Fiction
Science_Fiction

Reputation: 3433

Task creating another Task

for (int i = 0; i < someNumber; i++)
{
    Task<myObject>.Run(() => 
    {
       // some work
       // ...
       Task<myObjectNew>.Run(() => { // other work });
    });
}

I have a loop which creates lots of initial tasks (say upto 100). Then each of these tasks does some small unit of work and then creates another task itself. What I am noticing is that non of the initial 100 tasks start until all have been setup.

If the initial Task creates a Thread as opposed to another Task then things seem fine and as soon as the first outer task is created it begins executing (and spawns off a new Thread etc).

I've not seen behavior like before but then again I've not had a Task create another Task.

Any ideas?

Upvotes: 0

Views: 240

Answers (2)

Sebastian Schumann
Sebastian Schumann

Reputation: 3446

Tasks are scheduled using threadpool worker threads. If you want to bypass the threadpool you can declare your Task as LongRunning that will start a new thread immediately.

If you need some more information about it: https://msdn.microsoft.com/en-us/library/ff963549.aspx

Upvotes: 0

Peter Duniho
Peter Duniho

Reputation: 70661

The Task<T> objects are managed through the thread pool, and are limited in terms of how quickly they are started. I don't recall the current defaults off the top of my head, but the basic idea is that once the thread pool is out of threads, new threads are created only at the rate of one per second (or so).

When you create a Thread object explicitly, there's no waiting. They are created and begun immediately. There may be a slightly delay, on the order of dozens of milliseconds, before the thread actually gets its turn to start executing, but otherwise it's effectively instantaneous.

Upvotes: 1

Related Questions