我有我的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;
}
public async Task<List<int>> GenerateListAsync()
{
Console.WriteLine("Gonna generate the list async!");
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 asyncronously!");
await Task.Run(() => VeryHeavyCalculations());
i++;
}
return list;
}
public void VeryHeavyCalculations()
{
Thread.Sleep (1000);
}
}
}我期望list = await interesting.GenerateListAsync();在alsoList = interesting.GenerateList();运行时异步运行,在GenerateListAsync执行完全相同的操作时,有效地将GenerateList的输出记录到控制台中,或者在GenerateList完成时看到GenerateListAsync几乎立即结束。
但是,查看控制台,我看到我的应用程序运行GenerateListAsync,然后运行GenerateList。
我做错了,但没有足够的来源来解决这个问题。
发布于 2019-04-01 16:43:35
我希望
list = await interesting.GenerateListAsync();在alsoList = interesting.GenerateList();运行时异步运行,
这种期望是不正确的;await的全部要点是,在异步操作完成之前,不会在该点上继续运行;它使用一系列的技巧来实现这一点,包括异步状态机,这些机制允许在结果返回时恢复不完整的操作。但是,您可以移动await的位置,这样就不会造成这种明显的阻塞:
List<int> list;
List<int> alsoList;
var pending = interesting.GenerateListAsync(); // no await
alsoList = interesting.GenerateList();
list = await pending; // essentially "joins" at this point... kind of请注意,async和并行性是不同的;它们可以一起使用,但这不是默认情况。还要注意:并非所有的代码都是为了允许并发使用而设计的,所以在不知道在特定API上使用并发调用是否是OK的情况下,不应该这样做。
发布于 2019-04-01 18:31:23
至于答案,请看一下等待(C#参考)
将等待操作符应用于异步方法中的任务,以便在执行该方法时插入暂停点,直到等待的任务完成为止。这就是您的应用程序运行GenerateListAsync之后运行GenerateList的原因。要异步运行GenerateListAsync,您需要在任务变量中获取GenerateListAsync返回,然后调用GenerateList,然后使用EWAIT期待GenerateListAsync方法。
e.g
Task <List<int>> longRunningTask = interesting.GenerateListAsync();
alsoList = interesting.GenerateList();
list = await longRunningTask;https://stackoverflow.com/questions/55459812
复制相似问题