C# 任务延续
我有一个Web API,可返回人员列表:C# 任务延续,c#,asp.net-web-api,task-parallel-library,C#,Asp.net Web Api,Task Parallel Library,我有一个Web API,可返回人员列表: public async Task<HttpResponseMessage> Get() { var people = await _PeopleRepo.GetAll(); return Request.CreateResponse(HttpStatusCode.OK, people); } 我走远了吗?打个电话就行了 List<Person> persons = await GetAllPeople(); P
public async Task<HttpResponseMessage> Get()
{
var people = await _PeopleRepo.GetAll();
return Request.CreateResponse(HttpStatusCode.OK, people);
}
我走远了吗?打个电话就行了
List<Person> persons = await GetAllPeople();
PrintPeopleList(persons);
List persons=wait GetAllPeople();
打印人员名单(人);
GetAllPeople
已经返回了一个任务
,因此您不需要使用StartNew
。如果存在PrintPeopleList(),则不会调用服务方法。如果我将对PrintPeopleList()的调用注释掉,它将调用服务方法。知道为什么吗?那不可能是真的。也许是魔法?PrintPeopleList
与服务调用的关系如何?无,因为它只迭代提供给它和控制台的列表。WriteLine是每个列表项的ToString()。
static void PrintPeopleList(List<Person> people)
{
if (people == null)
{
Console.Write("No people to speak of.");
return;
}
people.ForEach(m => Console.WriteLine(m.ToString()));
}
Task.Factory.StartNew(() => GetAllPeople()).ContinueWith((t) => PrintPeopleList(t.Result));
List<Person> persons = await GetAllPeople();
PrintPeopleList(persons);