我正在学习 C# 中的异步,并希望每三秒显示一个程序运行时。我有两种解决方案,但都不能完全正常工作。
解决方案1
在第一个解决方案中,我有一个循环调用两个方法。第一个执行计算,第二个显示可被 3 整除的启动时间。
namespace Async
{
class Program
{
static void Main(string[] args)
{
PerformLoop();
Console.ReadLine();
}
public static async void PerformLoop()
{
Stopwatch timer = new Stopwatch();
timer.Start();
List<Task> l = new List<Task>();
for (int i = 0; i < 50; i++)
{
l.Add(AsyncCalculation(i));
l.Add(ShowTime(Convert.ToInt32(timer.Elapsed.TotalMilliseconds)));
}
await Task.WhenAll(l);
timer.Stop();
Console.WriteLine("Total execution time: " +
timer.Elapsed.TotalMilliseconds);
}
public async static Task AsyncCalculation(int i)
{
var result = 10 * i;
Console.WriteLine("Calculation result: " + result);
} …Run Code Online (Sandbox Code Playgroud)