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);
}
}
}
request thread (ASP.NET thread) starts the GetAsync method and calls DoComplexCalculusAsync() asynchronously. Inside DoComplexCalculusAsync(), Task. Run uses another new thread from thread pool to do the heavy calculations in the background.
WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.
A task is something you want done. A thread is one of the many possible workers which performs that task. In . NET 4.0 terms, a Task represents an asynchronous operation.
Task. WaitAll blocks the current thread until everything has completed. Task. WhenAll returns a task which represents the action of waiting until everything has completed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With