无法从任务列表中获得结果

时间:2017-09-15 17:25:15

标签: c# async-await

我有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 :(
    }
}

如何从任务中获取数据?

1 个答案:

答案 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);