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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With