Method return a task, how get the return-value?

2019-01-29 14:22发布

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?

2条回答
可以哭但决不认输i
2楼-- · 2019-01-29 15:06

You need to use await to get the result of an async method:

var myList = await GetList();

To use await the method that you call GetList from should be async too.If it's not you can use .Result property, but this will block the execution:

var myList = GetList().Result;
查看更多
不美不萌又怎样
3楼-- · 2019-01-29 15:10

You await it, like this:

var myList = new List<String>();
myList = await GetList();

Note that according to the Task-based Asynchronous Pattern, GetList should have an Async suffix, which tips off developers that it should be awaited:

var myList = new List<String>();
myList = await GetListAsync();

And, of course, creating a new list just to throw it away is silly:

var myList = await GetListAsync();
查看更多
登录 后发表回答