【发布时间】:2019-05-21 09:16:17
【问题描述】:
在 MapLocationFinder 的等待下,我的程序仍在运行,即使在尝试使用 Application.Current.Shutdown(); 关闭它之后也是如此。我是初学者。
我已经尝试使用 CancellationToken 或将其作为任务运行。但我不知道我是否以正确的方式做到了这一点。我尝试了几个小时的不同想法,但没有任何效果。
private async Task GetLocation()
{
var accesStatus = await Geolocator.RequestAccessAsync();
switch (accesStatus)
{
case GeolocationAccessStatus.Allowed:
// locate user
var locator = new Windows.Devices.Geolocation.Geolocator();
var location = await locator.GetGeopositionAsync();
var position = location.Coordinate.Point.Position;
// get city name
Geopoint geopoint = new Geopoint(new BasicGeoposition
{
Latitude = position.Latitude,
Longitude = position.Longitude
});
问题从这里开始
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(geopoint, MapLocationDesiredAccuracy.Low);
if (result.Status == MapLocationFinderStatus.Success)
{
locationBlock.Text = "City: " + result.Locations[0].Address.Town;
}
问题结束,剩下的只是为了上下文
// calculate time
int[] sun = SunDate.CalculateSunriseSunset(51.434406, 6.762329);
var sunrise = new DateTime(1, 1, 1, sun[0] / 60, sun[0] - (sun[0] / 60) * 60, 0);
var sunset = new DateTime(1, 1, 1, sun[1] / 60, sun[1] - (sun[1] / 60) * 60, 0);
//fit UI
lightStartBox.Text = sunrise.Hour.ToString();
darkStartBox.Text = sunset.Hour.ToString();
// apply settings
lightStartBox.IsEnabled = false;
darkStartBox.IsEnabled = false;
break;
case GeolocationAccessStatus.Denied:
locationCheckBox.IsChecked = false;
locationBlock.Text = "The App needs permission to location";
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
break;
case GeolocationAccessStatus.Unspecified:
locationCheckBox.IsChecked = false;
locationBlock.Text = "The App needs permission to location";
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
break;
}
return;
}
如果我关闭程序,它也应该结束等待任务。更好:他得到信息后应该结束手术。
【问题讨论】:
-
如果所有这些都在事件处理程序(或单独的线程)中完成,也许使用CancellationTokenSource 会起作用?
标签: c# wpf uwp async-await task