I read several sources about async / await, where it was written that these constructions supposedly do not create any additional threads.
I decided to write a test code:
public static void Main() { var t = Test(); t.Wait(); } static async Task Test() { var t = Test2(); for (; ; ) { await Task.Delay(1000); Console.WriteLine("0"); } } static async Task Test2() { for (; ; ) { await Task.Delay(1000); Console.WriteLine("1"); } } So, Visual Studio shows that 2 threads were created.
- The main thread that went to handle one of the asynchronous methods
- Another was created to handle the second asychron task.
And sometimes, according to the debager, there are 3 of them.
How so?
Or all the same, threads are not created using only IO operations, and with some computational threads, does the CLR determine the need to create a stream?
Or was it understood by “does not create threads” that ready-made threads are taken from the pool, but do you have a lot of threads in a program at a time?
Or mean that tries to use as few streams as possible? So if 2 asynchronous operations are spinning and they are not suppressed by the execution time, then 1 thread is used, and if they are spinning in parallel, then is CLR advantageous to turn 2 threads?
TaskAwaiter.OnCompletedupon completion ofTasksimply places the task in the thread pool for the execution of the next synchronous part of the suspended method. Next, the thread pool itself decides how (whether or not to create a new thread, and so on) for it to perform the tasks placed in it. - PetSerAl