Task.WhenAll () - does a new thread create?

According to MSDN :

Creates a task that will be completed after all tasks have been completed.

When Task.WhenAll () is called, it creates a task, but does this necessarily mean that it creates a new thread to perform this task? For example, how many threads are created in this console application below?

class Program { static void Main(string[] args) { RunAsync(); Console.ReadKey(); } public static async Task RunAsync() { Stopwatch sw = new Stopwatch(); sw.Start(); Task<string> google = GetString("http://www.google.com"); Task<string> microsoft = GetString("http://www.microsoft.com"); Task<string> lifehacker = GetString("http://www.lifehacker.com"); Task<string> engadget = GetString("http://www.engadget.com"); await Task.WhenAll(google, microsoft, lifehacker, engadget); sw.Stop(); Console.WriteLine("Time elapsed: " + sw.Elapsed.TotalSeconds); } public static async Task<string> GetString(string url) { using (var client = new HttpClient()) { return await client.GetStringAsync(url); } } } 
+7
c # asynchronous task-parallel-library async-await
source share
1 answer

WhenAll does not create a new thread. "Task" does not necessarily imply flow; There are two types of tasks: "event" tasks (for example, TaskCompletionSource ) and "code" tasks (for example, Task.Run ). WhenAll is an event style task, therefore, it is not code. If you are new to async , I recommend starting with my introductory blog post .

Your test application will use thread pool threads and IOCP threads as needed to complete async methods, so it can work with an integer number of threads or as many as 5. If you are interested in how exactly streaming works, you can check out my recent blog post async .

+9
source share

All Articles