【发布时间】:2020-12-06 18:00:51
【问题描述】:
这是我为更好地理解异步方法而编写的代码。我知道异步方法与多线程不同,但在这种特定情况下似乎并非如此:
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
//the line above just makes sure that the console output uses . to represent doubles instead of ,
ExecuteAsync();
Console.ReadLine();
}
private static async Task ParallelAsyncMethod() //this is the method where async parallel execution is taking place
{
List<Task<string>> tasks = new List<Task<string>>();
for (int i = 0; i < 5; i++)
{
tasks.Add(Task.Run(() => DownloadWebsite()));
}
var strings = await Task.WhenAll(tasks);
foreach (var str in strings)
{
Console.WriteLine(str);
}
}
private static string DownloadWebsite() //Imitating a website download
{
Thread.Sleep(1500); //making the thread sleep for 1500 miliseconds before returning
return "Download finished";
}
private static async void ExecuteAsync()
{
var watch = Stopwatch.StartNew();
await ParallelAsyncMethod();
watch.Stop();
Console.WriteLine($"It took the machine {watch.ElapsedMilliseconds} milliseconds" +
$" or {Convert.ToDouble(watch.ElapsedMilliseconds) / 1000} seconds to complete this task");
Console.ReadLine();
}
}
//OUTPUT:
/*
Download finished
Download finished
Download finished
Download finished
Download finished
It took the machine 1537 milliseconds or 1.537 seconds to complete this task
*/
如您所见,DownloadWebsite 方法等待 1.5 秒,然后返回“a”。名为ParallelAsyncMethod 的方法将其中五个方法添加到“任务”列表中,然后开始并行异步执行。如您所见,我还跟踪了执行ExecuteAsync 方法所需的时间。结果总是在 1540 毫秒左右。这是我的问题:如果DownloadWebsite 方法需要一个线程在1500 毫秒内休眠5 次,这是否意味着这些方法的并行执行需要5 个不同的线程?如果不是,那为什么程序只用了 1540 毫秒而不是 ~7500 毫秒?
【问题讨论】:
-
@John Wu 我读过。这是一篇很棒的文章。
标签: c# multithreading asynchronous parallel-processing async-await