我正在开发 WinPhone 8 应用程序。 在此应用程序上有一个按钮“发送短信”。 当用户点击这个按钮时,会发生两件事:
- (方法 A)获取当前位置的地理坐标(使用 Geolocator 和 GetGeopositionAsync)。
- (方法 B)撰写并发送一条将地理坐标作为正文的一部分的 SMS。
问题:GetGeopositionAsync 是一种异步方法。在检测到坐标之前(这需要几秒钟)发送 SMS(当然没有坐标)。
如何让方法 2 等待坐标可用?
好的,这是我的代码:
当用户按下按钮时,坐标由第一种方法确定,第二种方法发送包含坐标的 SMS:
private void btnSendSms_Click(object sender, RoutedEventArgs e)
{
GetCurrentCoordinate(); // Method 1
// -> Gets the coordinates
SendSms(); // Method 2
// Sends the coordinates within the body text
}
第一个方法 GetCurrentCoordinate() 如下所示:
...
private GeoCoordinate MyCoordinate = null;
private ReverseGeocodeQuery MyReverseGeocodeQuery = null;
private double _accuracy = 0.0;
...
private async void GetCurrentCoordinate()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(
TimeSpan.FromMinutes(1),
TimeSpan.FromSeconds(10));
lblLatitude.Text = currentPosition.Coordinate.Latitude.ToString("0.000");
lblLongitude.Text = currentPosition.Coordinate.Longitude.ToString("0.000");
_accuracy = currentPosition.Coordinate.Accuracy;
MyCoordinate = new GeoCoordinate(
currentPosition.Coordinate.Latitude,
currentPosition.Coordinate.Longitude);
if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy)
{
MyReverseGeocodeQuery = new ReverseGeocodeQuery();
MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(
MyCoordinate.Latitude,
MyCoordinate.Longitude);
MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted;
MyReverseGeocodeQuery.QueryAsync();
}
}
catch (Exception)
{ // Do something }
}
private void ReverseGeocodeQuery_QueryCompleted(object sender,
QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
lblCurrAddress.Text = address.Street + " " + address.HouseNumber + ",\r" +
address.PostalCode + " " + address.City + ",\r" +
address.Country + " (" + address.CountryCode + ")";
}
}
}
}
还有方法“SendSms()”:
private void SendSms()
{
SmsComposeTask smsComposeTask = new SmsComposeTask();
smsComposeTask.To = "0123456";
smsComposeTask.Body = "Current position: \rLat = " + lblLatitude.Text +
", Long = " + lblLongitude.Text +
"\r" + lblCurrAddress.Text;
// -> The TextBoxes are still empty!
smsComposeTask.Show();
}
问题是,当方法 SendSms() 设置 SmsComposeTask 对象时,所有这些文本框(lblLatitude、lblLongitude、lblCurrAddress)仍然是空的。
我必须确保在 SendSms() 方法启动之前已经设置了文本框。
请您参考如下方法:
您几乎应该永远不要将方法标记为async void,除非它是一个 UI 事件处理程序。您在不等待异步方法结束的情况下调用它。您基本上是在并行调用这 2 个方法,所以很清楚为什么坐标不可用。
您需要让 GetCurrentCoordinate 返回一个可等待的任务并等待它,如下所示:
private async Task GetCurrentCoordinateAsync()
{
//....
}
private async void btnSendSms_Click(object sender, RoutedEventArgs e)
{
await GetCurrentCoordinateAsync();
// You'll get here only after the first method finished asynchronously.
SendSms();
}
