-1

I need the others code lines wait the getUserLocal finish its job and return the value to they run, mainly the InitializeComponent();. I used wait but it seems doesn't work and when the components are initialized, I haven't had the getUserLocal result yet...

this is the constructor of my view

 public ComoChegarView(double lat, double longi)
    {
        userLocal = new Localizacao();
        getUserLocal();
        Localizacao lojaLocal =  new Localizacao();
        lojaLocal.latitude = lat;
        lojaLocal.longitude = longi;

        InitializeComponent();
     }

This is the async task

 async Task getUserLocal()
    {
        userLocal =  await Geolocator.GetUserLocationAsync();
    }

Does someone know how I can do that?

Joyce de Lanna
  • 1,473
  • 2
  • 15
  • 39
  • 3
    See [Async OOP 2: Constructors](https://blog.stephencleary.com/2013/01/async-oop-2-constructors.html). – Dustin Kingen Aug 04 '17 at 16:47
  • See discussion here making async constructors is actively being talked about in csharp. github.com/dotnet/csharplang/issues/419. – Shawn Aug 04 '17 at 17:07
  • 1
    Well, if you want to keep this design than you may try `Task.Run(async () => await getUserLocal()).Wait();` Your constructor will block while the `async` method will be awaited asynchronously on one of the threads from the pool. It's not the best move but It will work if `GetUserLocationAsync` does not need UI context to work. – Sergey.quixoticaxis.Ivanov Aug 04 '17 at 17:17
  • It worked for me Thank you very much!!! – Joyce de Lanna Aug 04 '17 at 17:21

1 Answers1

0

You can't call async methods from your constructor, that should be more obvious when you can't mark your constructor as async, which leads to you not being able to await the result of your async method.

IvanJazz
  • 763
  • 1
  • 7
  • 19