6

I have this async function that returns a 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;
    }
}

Now I want to get all settings and then wait until all is completed like this

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

How to get the data from the task?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Nigor
  • 83
  • 1
  • 5

1 Answers1

11

Change your taskList to List<Task<SettingModel>> and also don't use task.Result to avoid Deadlock. Your code should be something like this:

var taskList = new List<Task<SettingModel>>();

foreach(var key in keys)
{
    taskList.Add(GetSetting(key));
}

var result = await Task.WhenAll(taskList.ToList()).ConfigureAwait(false);
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 3
    Since all tasks are awaited in `await Task.WhenAll` in OP's case, `.Result` wouldn't cause deadlock. (Of course better to avoid it if you are not sure about what you are doing) – L.B Sep 15 '17 at 17:47
  • Great answer! Thanks for your help. – Gino Mortillero Sep 12 '19 at 01:19