Task Id in Nested Asynchronous Operation in C#

Shervan360 1,481 Reputation points
2022-08-13T21:55:38.957+00:00

Hello,

I expected the task number in Line 24 to be 8, since we are in the orange area with Task Id 8 but seems UI thread executed Line 24.
Could you please explain it?

231004-screenshot-2022-08-13-173347.png

            static async Task Total()  
            {  
                Console.WriteLine($"START...{Task.CurrentId}");  
                Task task = Task.Run(async () =>  
                {  
                    Console.WriteLine($"First...{Task.CurrentId}");  
                    await Task.Run(() =>  
                    {  
                        Console.WriteLine($"Second...{Task.CurrentId}");  
                    });  
                    Console.WriteLine($"Third...{Task.CurrentId}");  
                });  
            }  
  
  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2022-08-15T15:11:25.53+00:00

    When you call await, the lines following are run on a new thread from the thread pool, because they are really an async callback from the Awaitable code.

    The calling thread is done when it calls the await code, and returns to the thread pool. it might ne more obvious if you looked at the code without awaits:

    Task task = Task.Run(() =>  
     {  
          Console.WriteLine($"First...{Task.CurrentId}");  
          Task.Run(() =>  
          {  
              Console.WriteLine($"Second...{Task.CurrentId}");  
          }).ContinueWith(() =>  
          {  
               Console.WriteLine($"Third...{Task.CurrentId}");  
          });  
    }  
      
    

    where ContinueWith, runs its delegate as a new task.

    0 comments No comments