GMap.NET WPF 标记计时器更新

GMap.NET WPF Marker timer update

我使用线程的经验很少,所以我的逻辑中可能会遗漏一些非常基本的信息。

无论如何,我正在尝试更新基于 1000 毫秒计时器的 GMapMarker。

我的计时器开始:

aTimer = new System.Timers.Timer();
aTimer.Elapsed += OnTimerEvent;
aTimer.Interval = 1000;
aTimer.Enabled = true;

我的更新码:

int _positionIncriment = 0;
private  void OnTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    PointLatLng p = m_debugPath[_positionIncriment];
    _gpsMarker.Position = p;
    _positionIncriment++;

    _gmap.ForceUpdateOverlays();

    if(_positionIncriment >= m_debugPath.Count)
    {
        _positionIncriment = 0;
    }
}

当我逐步执行此块时,它在 ForceUpdateOverlays 处停止并且再也没有进行过。 据我所知,GMap 的渲染函数在它自己的线程中,这可能会导致问题……但正如我所说,我对线程只有基本的了解,我有点迷茫。 任何帮助都会很棒。

看来我需要在 运行 我的代码之前调用 Dispatcher。 我不知道这是解决这个问题的 'correct' 方法,但最终结果是我想要的。

希望这对其他人有帮助。

int _positionIncrement = 0;
private  void OnTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    this.Dispatcher.Invoke(() =>
    {
        PointLatLng p = m_debugPath[_positionIncrement];
        _gps.Position = p;
        _positionIncrement++;

        _gmap.ForceUpdateOverlays();

        if(_positionIncrement >= m_debugPath.Count)
        {
            _positionIncrement = 0;
        }
    });
}

使用 DispatcherTimer 而不是 Timer。它的 Tick 事件在 UI 线程中触发:

using System.Windows.Threading;
...

aTimer = new DispatcherTimer();
aTimer.Tick += OnTimerEvent;
aTimer.Interval = TimeSpan.FromSeconds(1);
aTimer.IsEnabled = true; // or aTimer.Start();
...

private void OnTimerEvent(object sender, EventArgs e)
{
    ...
}