I want to use ToDictionary
on a bunch of Task<MyObject>
(see below). This works ok if I use TheTask.Result
, but not await
This works:
Dictionary<CarId, Task<Model>> allModelTasks = carIds.ToDictionary(cId =>cId, cId=> GetModelForCar(cId));
await Task.WhenAll(allModelTasks.Values);
Dictionary<CarId, Model> allModels = allModelTasks.ToDictionary(mt => mt.Key, mt => mt.Value.Result);
But if I replace last row with
Dictionary<CarId, Model> allModels = allModelTasks.ToDictionary(mt => mt.Key, async mt => await mt.Value);
I get an error message that says "cant convert from Dict<CarId, Task<Model>>
to Dict<CarId, Model>
".
As I see it, the rows should be equivalent.
(The recommendation from here, seems to be to use await instead of .Result
, even after EDIT Task.WhenAll
)