2014-03-31 71 views
1

我有一個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)); 

我是否離開?

+2

'GetAllPeople'已經返回'Task'所以你不需要使用'StartNew'。 – Lee

回答

2

只需撥打

List<Person> persons = await GetAllPeople(); 
PrintPeopleList(persons); 
+0

使用PrintPeopleList()函數時,服務方法似乎不會被調用。如果我將PrintPeopleList()的調用註釋掉,它會調用服務方法。任何想法,爲什麼? – Bullines

+0

這不可能是真的。也許有些魔力?如何將PrintPeopleList與服務調用聯繫起來? –

+0

沒有,因爲它只遍歷提供給它的List以及Console.WriteLine的每個列表項的ToString()。 – Bullines