问题描述
根据 MSDN :
调用Task.WhenAll()时,它会创建一个任务,但这是否必然意味着它会创建一个新线程来执行该任务?例如,在下面的此控制台应用程序中创建了多少个线程?
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
不会创建新线程.一个任务"并不一定意味着一个线程.任务有两种类型:事件"任务(例如TaskCompletionSource
)和代码"任务(例如Task.Run
). WhenAll
是事件样式的任务,因此它不表示代码.如果您是async
的新手,建议您从我的入门博客文章开始
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.
您的测试应用程序将根据需要使用线程池线程和IOCP线程来完成async
方法,因此它可能仅以2个线程或最多5个线程运行.可以,您可以查看我的有关async
线程的最新博客帖子.
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.
这篇关于Task.WhenAll()-是否创建新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!