我有一個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));
我是否離開?
'GetAllPeople'已經返回'Task'所以你不需要使用'StartNew'。 – Lee