Forum Cross Platform with Xamarin

Main thread usage depending on device

I have found myself having to use:

Device.BeginInvokeOnMainThread(() =>
{
    // make ui changes here
});

... quiet frequently in my pretty thread intensive app that consumes sensors on the device. Since moving to a newer bought android api 28 device however I have been able to remove many of these calls without any problem. Recently I have start worrying though as this might break with older devices?

My thought is that the app when running on older devices might be more likely to put work async and on other threads - while with a newer device can let the app run more work on the UI thread (thus requiring less invoke on main thread directives)?

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    I think it's better to add this code to make sure your code has been run on the UI thread even though this application may run on api 28+ devices. We could use native code below to check current OS version on Android:

    if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.P)
    {
    
    }
    

    But I still suggest adding this code for compatible issues. It won't take too much time to add this simple code snippet but on the other hand, detecting the OS version still need some effort.
    Moreover, Forms is used to build a cross-platform project. It is not only served for Android. We still need to consider iOS and UWP parts. So if you want to run code on the main thread it's better to add this lambda to manually ensure it has been done.

Sign In or Register to comment.