我有我的 Program.cs 文件:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var interesting = new InterestingObject();
List<int> list;
List<int> alsoList;
list = await interesting.GenerateListAsync();
alsoList = interesting.GenerateList();
Console.WriteLine("Done! :)");
list .ForEach(xs => Console.WriteLine(xs));
alsoList.ForEach(xs => Console.WriteLine (xs));
}
}
}
这是 InterestingObject 的代码:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
public class InterestingObject
{
public InterestingObject()
{
}
public List<int> GenerateList()
{
Console.WriteLine("Gonna generate the list!");
var list = new List<int>();
int i = 0;
while (i < 5)
{
Random random = new Random();
list.Add(random.Next());
Console.WriteLine("Generated a new int!");
VeryHeavyCalculations();
i++;
}
return list;
}
我希望list = await interesting.GenerateListAsync();在运行时异步运行,在执行完全相同的操作时alsoList = interesting.GenerateList();有效地将输出记录GenerateList到我的控制台中,或者在完成时几乎立即看到完成。GenerateListAsyncGenerateListAsyncGenerateList
但是,查看控制台我看到我的应用程序正在运行GenerateListAsync然后运行GenerateList。
我做错了,但没有足够的资源来解决这个问题。
米琪卡哇伊
宝慕林4294392
相关分类