no worker thread create when Task has not started executing yet?

I'm reading a book on threads, below is the quote from the book:

When a thread calls the Wait method, the system checks if the Task that the thread is waiting for has started executing. If it has, then the thread calling Wait will block until the Task has completed running. But if the Task has not started executing yet, then the system may (depending on the TaskScheduler) execute the Task by using the thread that called Wait. If this happens, then the thread calling Wait does not block; it executes the Task and returns immediately

Let's say we have the following code:

static void Main(string[] args) {
   // Create a Task (it does not start running now)
   Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 10);


   Console.WriteLine("The Sum is: " + t.Result); 

static Int32 Sum(Int32 n) {
   Int32 sum = 0;
   for (; n > 0; n--)
       { sum += n; } 
   return sum;

My understanding is, t.Start(); means CLR will schedule it for execution so later a worker thread from threadpool can execute it. So let's say the main thread has reached to t.Wait(); while the task is still not executed by any worker thread (task has been scheduled but hasn't been picked up by the thread pool's worker thread).

Then main thread will actually execute the Sum method, is my understanding correct? So if I run the program a thousand of times, 99.99% Sum method will be executed by other worker thread, but 0.01% it will be executed by main thread. Currently no matter how many time I run the program it is always a woker thread to execute Sum method, this is just because the task always start to execute quicke before the main thread executes t.Wait();, if sth usunal happen, there is still a chance (0.01%) that the main thread can execute Sum method, is my understanding correct?

1 answer

  • answered 2021-05-14 04:41 DekuDesu

    if [the unusual happens], there is still a chance (0.01%) that the main thread can execute Sum method, is my understanding correct?

    The answer is possibly!

    This involves some serious deep-diving into the specific implementation details of how the TaskScheduler handles tasks that are queued and how the compiler and subsequent smoke and mirrors that run in the back-end of the MSDN language have implemented the state-machines that handle Tasks and async operations.

    But in the basic sense you're conclusion, in my opinion, is correct! Per MSDN, if you are using the default TaskScheduler, the TaskScheduler implements certain optimizations on your behalf such as Task Inlining, like you described, and other optimizations like Work Stealing.

    If work stealing and task inlining are not desirable, consider specifying a synchronization context of the tasks that you are creating, to prevent them from performing work on threads other than the ones you specify.