2015-10-13 31 views
-1

我有以下代碼如何獲取的方法異步C#的windows phone的值8.1

async void getLocation1() 
    { 
     try { 

      var geolocator = new Geolocator(); 
      Geoposition position = await geolocator.GetGeopositionAsync(); 

      // reverse geocoding 
      BasicGeoposition myLocation = new BasicGeoposition 
      { 
       Longitude = position.Coordinate.Longitude, 
       Latitude = position.Coordinate.Latitude             
      };        

      Geopoint pointToReverseGeocode = new Geopoint(myLocation); 
      MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode); 

      // here also it should be checked if there result isn't null and what to do in such a case 

      PostalCode1 = result.Locations[0].Address.PostCode; 
      Country1 = result.Locations[0].Address.Country; 
      City1 = result.Locations[0].Address.Town; 
      State1 = result.Locations[0].Address.Region; 

      guardarLatit = myLocation.Latitude.ToString(); 
      guardarLong = myLocation.Longitude.ToString(); 

      await GeolocationWait(); 

      MessageDialog msgbox3 = new MessageDialog("Latitud: " + guardarLatit + "Longitud: " + guardarLong); 
      MessageDialog msgbox4 = new MessageDialog("PostalCode: " + PostalCode1 + " Country: " + Country1 + "City: " + City1 + "State: " + State1); 

      geolocation.Add("Latitud: " + guardarLatit); 
      geolocation.Add("Longitud: " + guardarLong); 
      geolocation.Add("PostalCode: " + PostalCode1); 
      geolocation.Add("Country: " + Country1); 
      geolocation.Add("City: " + City1); 
      geolocation.Add("State: " + State1); 

      await msgbox3.ShowAsync(); 
      await msgbox4.ShowAsync(); 

     } catch (Exception ex) 
     { 
      MessageDialog msgboxE = new MessageDialog("Error"); 
      await msgboxE.ShowAsync(); 
      geolocation.Add("Latitud: null"); 
      geolocation.Add("Longitud: null"); 
      geolocation.Add("PostalCode: null"); 
      geolocation.Add("Country: null"); 
      geolocation.Add("City: null"); 
      geolocation.Add("State: null"); 
     } 
    } 

,但我需要做的是在相同的方法,無需異步方法的返回值,我一定會通過某種途徑告訴我所有的異步,它停止獲取該值。

我的問題是,當我打印經度和緯度零時拋出我,因爲異步方法發送的值肯定不是按時。

謝謝

+0

你在等待getLocation1()嗎? – kernanb

+0

我需要實時獲取緯度和經度的值作爲json上的打印,但總是將我拉到空,因爲異步方法稍後發送值 –

回答

0

好了,首先你要知道,你不應該使用異步無效。 這是一個允許你使用它的構造,但是如果你等待getLocation1()你的程序不會等待它。 相反,您應該在可能的情況下始終使用異步任務。因此,請嘗試將getLocation1更改爲異步任務,然後在您等待之後,確保其中已完成任務。

+0

謝謝,您向我指示的解決方案是將方法更改爲異步任務GetLocation() –

+0

那麼你能標記我的答案爲...答案? ;) – Festyk