I have a Google Map (MapFragment) with more than 5 markers on it. I want to update the position of markers for every 10-15 seconds. I will be getting new co ordinates via a API call.
我有一个谷歌地图(MapFragment),上面有超过5个标记。我想每10-15秒更新一次标记的位置。我将通过API调用获得新的坐标。
Is there any way we can update the markers without blocking the UI? Sample C# snippet for long polling would be awesome..
有没有什么方法可以在不阻止UI的情况下更新标记?用于长轮询的示例C#片段会很棒..
I tried doing -
我试过 -
RunOnUiThread(() =>
{
while(true){
//UPDATE MARKERS HERE
Thread.Sleep(5000);
}
}
but it freeze the UI. Is there any way to update markers without freezing UI?
但它冻结了UI。有没有办法更新标记而不冻结UI?
1 个解决方案
#1
Doing:
RunOnUiThread(() =>
{
while(true){
//UPDATE MARKERS HERE
Thread.Sleep(5000);
}
}
Forces everything inside of the anonymous method to run on the UI thread. So the while loop inclusive of the Thread.Sleep
is blocking the UI.
强制匿名方法内的所有内容在UI线程上运行。因此包含Thread.Sleep的while循环阻止了UI。
Instead you want to do your long operation asynchronously, for instance using TPL (async/await) in C#.
相反,您希望异步执行长时间操作,例如在C#中使用TPL(async / await)。
Dictionary<int, Marker> _markers = new Dictionary<int, Marker>();
async Task PollServerAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
var coordinates = await GetNewCoordinatesFromServerAsync(cancellationToken);
foreach (var coord in coordinates)
{
var marker = _markers[_coord.Id];
RunOnUiThread(() =>
{
marker.SetPosition(coord.Position);
});
}
await Task.Delay(5000, cancellationToken);
}
}
#1
Doing:
RunOnUiThread(() =>
{
while(true){
//UPDATE MARKERS HERE
Thread.Sleep(5000);
}
}
Forces everything inside of the anonymous method to run on the UI thread. So the while loop inclusive of the Thread.Sleep
is blocking the UI.
强制匿名方法内的所有内容在UI线程上运行。因此包含Thread.Sleep的while循环阻止了UI。
Instead you want to do your long operation asynchronously, for instance using TPL (async/await) in C#.
相反,您希望异步执行长时间操作,例如在C#中使用TPL(async / await)。
Dictionary<int, Marker> _markers = new Dictionary<int, Marker>();
async Task PollServerAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
var coordinates = await GetNewCoordinatesFromServerAsync(cancellationToken);
foreach (var coord in coordinates)
{
var marker = _markers[_coord.Id];
RunOnUiThread(() =>
{
marker.SetPosition(coord.Position);
});
}
await Task.Delay(5000, cancellationToken);
}
}