Search code examples
c#.netmultithreadingtaskthreadpool

Can same thread wait and run task simultaneously?


I'm following Walkthrough: Debugging a Parallel Application in Visual Studio from Microsoft documentation. And from section about Parallel Tasks window when hitting third breakpoint it clearly says:

In this example run, notice that task 11 and task 12 are running on the same thread (show the Thread Assignment column if it is hidden).

Tasks window From "Tasks window" we see that task 11 is "Blocked" and task 12 is "Active"

If we navigate to task's 11 location which is "O" method we can see that it's blocked on line t5.Wait();

static void O(object o)
  {
    Task t5 = Task.Factory.StartNew(P, TaskCreationOptions.AttachedToParent);
    t5.Wait(); // tasks 11 blocked here
    R(o);
  }

and then by inspecting "Tasks window" we can see that same thread(27500) has two tasks: task 11, which is blocked by calling t5.Wait() and task 12 which is active and runs "P" method as a new task. But how it's possible that single thread has blocked task and runs another at the same time?

I've debugged this walkthrough several times and i succeed to repeat same behavior only once randomly. Other times i saw, as i thought, correct behavior where task with method "P" always runs in another thread. Tasks window local debug

I thought, when thread calls task's "Wait" method, thread becomes blocked until tasks finishes? What did i miss here?


Solution

  • It is actually possible for the framework to inline the method in the current thread when calling Task.Wait, and this is logical. Why block the current thread when you can use it to execute the task. For this to happen a few conditions must be met.

    1. No timeout should be specified.
    2. No cancellation token should be given.
    3. The waiting thread shouldn't be the Main thread.
    4. Task must not started execution yet (Must be in WatingToRun state).

    If the task cannot be inlined, then the current thread blocks on Wait. This is described in short in the documentation of Wait.