According to MSDN :
Creates a task that will complete when all of the supplied tasks have completed.
When Task.WhenAll() is called, it creates a task but does that necessarily mean that it creates a new thread to execute that 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);
}
}
}
WhenAll
does not create a new thread. A "task" does not necessarily imply a thread; there are two types of tasks: "event" tasks (eg, TaskCompletionSource
) and "code" tasks (eg, Task.Run
). WhenAll
is an event-style task, so it does not represent code. If you're new to async
, I recommend starting with my introductory blog post .
Your test application will use thread pool threads and IOCP threads as necessary to finish the async
methods, so it may run with as few as 2 threads or as many as 5. If you're curious about how exactly the threading works, you can check out my recent blog post on async
threads .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.