Please help, i need to use the Geoposition pos variable which is in class UserLocation in a class MainPage but it keeps returning null ,this method initializes pos,
public Geoposition pos;
async public void preparePosition()
{
try
{
// Get the cancellation token.
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
//MessageTextbox.Text = "Waiting for update...";
// Get the position to derive the coordinates
_geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
pos = await _geolocator.GetGeopositionAsync().AsTask(token);
}
catch (System.UnauthorizedAccessException)
{
}
catch (TaskCanceledException)
{
}
finally
{
_cts = null;
}
}
then in class MainPage
UserLocation LocationData = new UserLocation();
Geoposition p = LocationData.pos;
but it returns null, iv also tried using a return method
public Geoposition getPosition()
{
preparePosition();
return pos;
}
//then
using p = LocationData.getPosition();
preparePosition() is async so it returns before the GPS hardware gets the position.
can i suggest
public async Task<GeoPosition> PreparePosition()
{
...
return pos;
}
You then have to call it from an async proc
public async void MyButtonClick(sender, e){
using (var p = await preparePosition()){
...
}
}
Of course you can only say using (var p= ...
if p
implements IDisposable
.
Problem is that your method preparePosition is async. It retrieves value of "pos" asynchronously but you are using it without waiting for its result.
First, change preparePosition signature to:
async public Task preparePosition()
{
...
}
Then it returns Task instead of void and you can wait on its completion.
Then change getPosition to:
public Geoposition getPosition()
{
preparePosition().Wait();
return pos;
}
I recommend reading some articles about how async/await work and how they should be used.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.