方法返回一个任务,如何得到返回值? [英] Method return a task, how get the return-value?
本文介绍了方法返回一个任务,如何得到返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以说我有这个code调用服务并返回一个任务:
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;
}
如果这个methpd仅返回一个字符串列表,我可以做这样的事情:
If this methpd simply returned a list of strings I could have done something like this:
var myList = new List<String>();
myList = GetList()
我怎样才能获得与任务相似的结果呢?我在想这个也许走错了路?当然,我应该能够分配方法(字符串列表),以 myList中
?
推荐答案
您需要使用等待
来获得的结果异步
方法:
You need to use await
to get the result of an async
method:
var myList = await GetList();
要使用等待
您调用方法的GetList
从应异步
too.If它不是你可以使用。结果
属性,但是这将阻止执行:
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;
这篇关于方法返回一个任务,如何得到返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文