-3

I got interface with method:

Task<Dictionary<long, Cars>> GetCars();

Thne I have VM:

private IList<Cars> m_cars;

public IList<Cars> MyCars
{
   get => m_cars;
}

and some method:

public override void Load()
{
  MyCars = someservice.GetCars();
}

But I can't do that. How to assing values from Dictionary to IList?

4est
  • 3,010
  • 6
  • 41
  • 63

1 Answers1

1
public async override void Load()
{
    var dictionary = await someservice.GetCars();
    MyCars = dictionary.Values.ToList();
}

If you for some unknown reason can't mark the method as async and therefor can't call await you have to call the asynchronous method GetCars() synchronously, which isn't really recommended because why is it asynchronous when you call it synchronously.

To do this you can simply call the .Result of the Task

public override void Load()
{
    MyCars = someservice.GetCars().Result.Values.ToList();
}

Here a demonstration of the given options

https://dotnetfiddle.net/XCqiLY

Rand Random
  • 7,300
  • 10
  • 40
  • 88
  • 3
    `async void`? Now what happens if `MyCars` is accessed again before `GetCars` has completed? – Johnathan Barclay Mar 19 '21 at 13:08
  • 1
    @JohnathanBarclay - I assumed Load being an event handler, maybe I am assuming incorrectly - if that isn't the case OP may want to read here - https://stackoverflow.com/questions/19415646/should-i-avoid-async-void-event-handlers - about `MyCars` I don't really care what happens in that case, if it isn't populated it will be null, no code of OP would give me any clue if that is okay or not – Rand Random Mar 19 '21 at 13:12
  • 1
    Ok, maybe it is, maybe it isn't, but that assumption should have been stated because only event handlers should be `async void`. Also, `MyCars` is get-only so this wouldn't compile. – Johnathan Barclay Mar 19 '21 at 13:25
  • But `MyCars = someservice.GetCars();` is in op codes and he say it can't cahnge it so i guess it compile somehow, no? perhaps just an other typo. And the set got deleted – Self Mar 19 '21 at 13:37
  • @Self No, OP's code will definitely not compile for a number of reasons. The OP only stated that the return type of `Load` could not be changed. – Johnathan Barclay Mar 19 '21 at 13:39
  • Task...does not containt a def to `Values` – 4est Mar 19 '21 at 13:46
  • `Dictionary = await Task>` after await it return dictionary, dictionary have `Values` – Genusatplay Mar 19 '21 at 14:32
  • @4est - as Genusatplay already mentioned you have to `await` the `Task` this will "resolve" the `Task` and simply return the `Result` of the `Task` which is `Dictionary` in your case – Rand Random Mar 19 '21 at 15:55
  • @4est - updated my answer – Rand Random Mar 19 '21 at 16:12