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

2019-04-06 12:21发布

问题:

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);
        }
    }
}

回答1:

WhenAll does not create a new thread. A "task" does not necessarily imply a thread; there are two types of tasks: "event" tasks (e.g., TaskCompletionSource) and "code" tasks (e.g., 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.