How to sleep thread in Xamarin android and ios?

I am creating an application for iOS and Android using the Xamarin cross platform. I have one project called "Core", and then one for iOS and one for Android.

In the shared project β€œCore”, I want to show the boot animation that I created and extracting the current location from the device. I can get my locationWatcher, launch it and directly call LocationWatcher.CurrentPosition, but since he just started viewing location updates, he still hasn't gotten any location.

My solution is to wait 2 seconds after it starts and then get the location. However, I do not want to wait asynchronously, I want the user interface to be blocked while waiting. This is because the user does not have to do anything until the current position is known.

I am currently achieving this by having a loop:

DateTime startTime = DateTime.Now(); while ( (DateTime.Now() - startTime).TotalMilliseconds() < 2000) { //Locking the UI here, but it what I want so it ok. } 

This seems like an ugly β€œhack” for something that in Java would just be β€œThread.sleep (2000)"

Is there a better way to do this?

+6
source share
2 answers

The multi-platform way with Xamarin Forms will consist of

 await Task.Delay(ms); 

Edit:

After reading that you really want to block mainthread heres the multi-platform way to block Thread:

 Task.Delay(ms).Wait() 
+4
source

Blocking the user interface stream is bad practice, because, among other things, this can cause the device to mark the application as "non-responsive." You are also not guaranteed that the position will be determined in two seconds, so at best your offer is only a partial correction.

What you really want to do is to block user interface input by disabling the ability to enter input (there should be methods to disable interface elements), and then see if there is a callback from the geolocation service when it determines your location. In the callback, re-enable the user interface elements. If such a callback does not exist, search for the location synchronously in the user interface thread using RunOnUIThread / InvokeOnMainThread so that the thread is blocked only until it returns.

If you still want to continue your decision,

 RunOnUiThread(() => Thread.Sleep(2000)); 

should do the trick, but I really recommend not doing this. On iOS you will need to do

 InvokeOnMainThread(() => Thread.Sleep(2000)); 
+1
source

All Articles