我有一个返回人员列表的Web API:
public async Task<HttpResponseMessage> Get()
{
var people = await _PeopleRepo.GetAll();
return Request.CreateResponse(HttpStatusCode.OK, people);
}
我有一个控制台应用程序,我希望能够调用它以便首先获取人员,然后迭代调用他们的ToString()方法,然后完成。
我有以下方法来吸引人们:
static async Task<List<Person>> GetAllPeople()
{
List<Person> peopleList = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:38263/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("People");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
peopleList = await response.Content.ReadAsAsync<List<Person>>();
}
}
return peopleList;
}
然后我有第二个函数来打印列表:
static void PrintPeopleList(List<Person> people)
{
if (people == null)
{
Console.Write("No people to speak of.");
return;
}
people.ForEach(m => Console.WriteLine(m.ToString()));
}
我尝试使用任务工厂首先使用GetAllPeople()下载人员列表,然后在响应返回时将结果提供给PrintPeopleList(),但编译器发出了模糊的调用错误:
Task.Factory.StartNew(() => GetAllPeople()).ContinueWith((t) => PrintPeopleList(t.Result));
我离开了吗?
答案 0 :(得分:2)
致电
List<Person> persons = await GetAllPeople();
PrintPeopleList(persons);