Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get result from task list

Tags:

c#

async-await

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?

like image 205
Nigor Avatar asked Sep 15 '17 17:09

Nigor


1 Answers

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);
like image 72
Salah Akbari Avatar answered Sep 28 '22 14:09

Salah Akbari