3

I have WPF project. I am working with GMap.Net. My project is about to show the buses location over the city. For a demo version I want to have list of points and change the marker position every 5 seconds. There are 2 problem. First of all I should mention that I do not have internet connection when presenting the demo version and the second one is that when I try to Sleep the Map doesn't show anything until all Thread.Sleeps() executed.

PointLatLng[] points = new PointLatLng[]
{
new PointLatLng(34.633400, 50.867886),
new PointLatLng(34.632469, 50.866215),
new PointLatLng(34.631213, 50.864210),
new PointLatLng(34.629314, 50.861153),
new PointLatLng(34.626737, 50.857140)
};

int i = -1;
do
{
i++;

GMapMarker marker = new GMapMarker(points[i]);
marker.Shape = new Control.Marker(0, 0, 65, 90);
MainMap.Markers.Add(marker);

System.Threading.Thread.Sleep(5000);

MainMap.Markers.RemoveAt(0);

if (i == 3) break; ;
} while (true);

After the execution of Do-While loop the Map will show. I try:

Task.Factory();

And

 BackgroundWorker

but I got the error because my code contains UI Controls. Is there any solution?

Meyssam Toluie
  • 1,061
  • 7
  • 21

2 Answers2

3

You can use await Task.Delay(5000); instead of Thread.Sleep(5000);. Note that your method should be marked as async. Here's an example:

public async Task MyMethod(){
    // ^^^^^ async keyword here
    PointLatLng[] points = new PointLatLng[]
    {
        new PointLatLng(34.633400, 50.867886),
        new PointLatLng(34.632469, 50.866215),
        new PointLatLng(34.631213, 50.864210),
        new PointLatLng(34.629314, 50.861153),
        new PointLatLng(34.626737, 50.857140)
    };

    int i = -1;
    do
    {
        i++;

        GMapMarker marker = new GMapMarker(points[i]);
        marker.Shape = new Control.Marker(0, 0, 65, 90);
        MainMap.Markers.Add(marker);

        await Task.Delay(5000);
        //^^^ await keyword here
        MainMap.Markers.RemoveAt(0);

        if (i == 3) break;
    } while (true);
}
Nasreddine
  • 36,610
  • 17
  • 75
  • 94
0

If you are going to use sleep, it will need to be in a background thread. If you are running a method on the main UI thread and you sleep, the UI will sleep. Look into the BackgroundWorker class. https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx

Probably a better option would be to use a DispatchTimer and set the interval to 5 seconds, firing of your code in the timer tick method https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=vs.110).aspx.

hawkstrider
  • 4,141
  • 16
  • 27