Xamarin.Forms - BeginInvokeOnMainThread for an async Action

后端 未结 3 1959
我寻月下人不归
我寻月下人不归 2021-01-19 01:02

I am familiar with the rules about updating UI elements on the UI thread using the Device.BeginInvokeOnMainThread, however I have an operation that needs to be run on the UI

3条回答
  •  余生分开走
    2021-01-19 01:21

    Just make sure you handle exceptions in your Action and you should be fine. The problem you described occurs when you don't handle the exceptions. Below is a very simple example of running an async method from the main thread.

    private void Test()
    {
        Device.BeginInvokeOnMainThread(SomeMethod);
    }
    
    private async void SomeMethod()
    {
        try
        {
            await SomeAsyncMethod();
        }
        catch (Exception e) // handle whatever exceptions you expect
        {
            //Handle exceptions
        }
    }
    
    private async Task SomeAsyncMethod()
    {
        await Navigation.PushModalAsync(new ContentPage());
    }
    

提交回复
热议问题