我有async
函数返回Task
public async Task<SettingModel> GetSetting(string key)
{
var rootPath = _hostingEnvironment.ContentRootPath;
using (StreamReader r = new StreamReader(rootPath + key + "settings.json"))
{
string json = await r.ReadToEndAsync();
var settings = JsonConvert.DeserializeObject<SettingModel>(json);
return settings;
}
}
现在我想获得所有设置,然后等到所有设置完成后才会这样
public async Task GetData(List<string> keys)
{
var taskList = new List<Task>();
foreach(var key in keys)
{
taskList.Add(GetSetting(key));
}
await Task.WhenAll(taskList.ToList());
foreach (var task in taskList)
{
task.Result // here its not working. The task don't have a result :(
}
}
如何从任务中获取数据?
答案 0 :(得分:6)
将您的taskList
更改为List<Task<SettingModel>>
,也不要使用task.Result
来避免Deadlock。你的代码应该是这样的:
var taskList = new List<Task<SettingModel>>();
foreach(var key in keys)
{
taskList.Add(GetSetting(key));
}
var result = await Task.WhenAll(taskList.ToList()).ConfigureAwait(false);