为一位遛狗的朋友做了一个快速的应用程序,他想知道他走多远,速度和准确度高。无论如何,我通过计时器使应用程序跟踪距离和位置。一切正常,但是当更新屏幕上的统计数据(每8秒执行一次)时,似乎存在性能问题,因为时间将暂停,然后跳跃2秒,好像说更新部分需要一秒或2.
这是代码
List<GeoCoordinate> Locations;
Geolocator Locator = new Geolocator();
Locator.DesiredAccuracy = PositionAccuracy.High;
Locator.MovementThreshold = 1;
Locator.PositionChanged += Locator_PositionChanged;
DispatcherTimer _timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Tick += Timer_Tick;
_timer.Start();
long _startTime = System.Enviroment.TickCount;
private void Locator_PositionChanged(Geolocator sender, PostionChangedEventArgs args)
{
CurrentLocation = args.Position;
if(GetPositionTime >= 8) // Checks to see if 8 seconds has passed
{
Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
{
GeoCoordinate cord = new GeoCoordinate(CurrentLocation.Coordinate.Latitude,
CurrentLocation.Coordinate.Longitude);
if(Locations.Count > 0)
{
GeoCoordinate PreviousLocation = Locations.Last();
// This part will update the stats on the screen as a textbox is bound to
// DistanceMoved
DistanceMoved = cord.GetDistanceTo(PreviousLocation);
}
Locations.Add(cord);
}));
}
}
private void Timer_Tick(object sender, EventArgs e)
{
GetPositionTime++;
TimeSpan time = TimeSpan.FromMilliseconds(System.Enviroment.TickCount - _startTime);
// Update the timer on the screen
Duration = time.ToString(@"hh\:mm\:ss");
}
答案 0 :(得分:0)
需要在UI线程上更新UI控件 - 包装Dispatcher.BeginInvoke 在持续时间周围,它应该工作。
Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
{
Duration = time.ToString(@"hh\:mm\:ss");
}