2

Referring to the following post, which leads one to believe a .NET Task executes without native OS threads being involved. Is this true?

Difference between Task (System.Threading.Task) and Thread

EDIT

In reviewing duplicate questions I couldn't find an answer directly addressing the question that instantiating a .NET Task class will ultimately execute on a native OS thread. They refer to threads but either not discerning between managed and native OS threads or just to managed threads. The only thing that could be duplicate is my own answer to one of those questions.

But in digging myself, it would seem there is no "magic" with .NET that avoids native OS threads. There are no changes to the Windows kernel to allow this. Such is consistent with my own OS experience a couple of decades ago. In short, there is no app code anyone can write that does not run on a native Windows OS thread.

About Processes and Threads Managed Threading

Also:

Windows Kernel Internals Process Architecture

Architecture of the Windows Kernel

Evolution of the Windows Kernel Architecture

  • 2
    All code runs on native OS threads. Tasks don't use _a dedicated_ native thread. – SLaks Dec 27 '18 at 22:03
  • SLaks is correct. –  Dec 28 '18 at 14:44
  • See [Does each managed thread have its own corresponding native thread?](https://stackoverflow.com/questions/19476595/does-each-managed-thread-have-its-own-corresponding-native-thread) – wp78de Dec 29 '18 at 00:54

1 Answers1

5

The answer is: it depends.

Tasks which involve some computational work, would run on a thread and normally that would be a thread from the thread pool.

Long-running tasks, i.e. created with option TaskCreationOptions.LongRunning run on a dedicated thread, which is created for them.

I/O Tasks, like await stream.ReadAsync() do not have a thread at all. The operation is sent to the IO device, and the CPU is free to do whatever it pleases. Only when the device is ready with the requested data, it interrupts the CPU, it does some low-level processing and ultimately the OS gets a thread from the thread-pool to complete the task and make the result available to your program. More details here.

Nick
  • 4,787
  • 2
  • 18
  • 24