Search code examples
c#wpfgmap.net

How Make my project sleep without Thread.Sleep()?


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?


Solution

  • 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);
    }