Lets say I have this code that calls a service and returns a task:
public async Task<List<string>> GetList()
{
client.BaseAddress = new Uri("http://localhost9999/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/listofstrings");
var json = response.Content.ReadAsStringAsync().Result;
var myStr = JsonConvert.DeserializeObject<List<string>>(json);
var list = new List<string>(myStr);
return list;
}
If this methpd simply returned a list of strings I could have done something like this:
var myList = new List<String>();
myList = GetList()
How can i get a similar result with the Task? Am i thinking about this the wrong way maybe? Surely I should be able to assign the result of the method (a list of strings) to myList
?
You need to use
await
to get the result of anasync
method:To use
await
the method that you callGetList
from should beasync
too.If it's not you can use.Result
property, but this will block the execution:You
await
it, like this:Note that according to the Task-based Asynchronous Pattern,
GetList
should have anAsync
suffix, which tips off developers that it should beawait
ed:And, of course, creating a new list just to throw it away is silly: