Alan2
Alan2

Reputation: 24592

Can I change the UI from a method that gets data (not async) that has been called with await?

I have this code:

    protected override async void OnAppearing()
    {
        base.OnAppearing();            
        Subscribe();
        vm.IsBusy = true;
        if (Change.firstTimeCardsTab == true)
        {
            SetButtons(Settings.cc.ShortText());
            await Task.Run(() => GetOnAppearingData());
        }
    }

    private void GetOnAppearingData()
    {
        App.DB.GetData();
        AddDetailSection();
        SetPageDetails();
        Change.firstTimeCardsTab = false;
        vm.IsBusy = false;
    }

vm.IsBusy = true; shows an activity indicator on the page and vm.IsBusy = false; would I hoped turn it off.

However when I run the code I get a message saying:

UIKit Consistency error: you are calling a UIKit method that can only be invoked from a UI thread.

Can someone give me advice on how I can set the activity indicator to show, then get the data and then set it to not show? Note that AddDetailSection(); adds some elements to the XAML. Could this be the problem?

Upvotes: 0

Views: 88

Answers (1)

EvZ
EvZ

Reputation: 12179

UI can be manipulated only from the main thread. There is a method Device.BeginInvokeOnMainThread(Action) that can help to solve your issue, more can be found in the official documentation.

Just wrap all UI related actions by it:
Device.BeginInvokeOnMainThread(() => { SetPageDetails(); // Any other actions });

Upvotes: 1

Related Questions