I'm trying to write an async method which should be called from a background thread. The method should open a modal page, read some input fields, close the modal page and return the read values.
This is my method:
public static async Task<PasswordDialogValues> OpenPasswordDialog()
{
var vm = new PasswordFormViewModel();
Device.BeginInvokeOnMainThread(async () =>
{
var pwPage = new ModalContentPage()
{
WidthRequest = 380,
HeightRequest = 310,
BindingContext = vm,
Content = new PasswordFormView(),
};
await MainPage.Navigation.PushModalAsync(pwPage);
});
var values = await vm.GetValues(); //.ConfigureAwait(false);
Device.BeginInvokeOnMainThread(async () =>
{
Debug.WriteLine("OpenPasswordDialog: starting PopModalAsync()");
await MainPage.Navigation.PopModalAsync();
Debug.WriteLine("OpenPasswordDialog: PopModalAsync() finished");
}
);
return values;
}
It works on the iPad. But on the iPhone simulator the app crashes and leaves this in my output window:
[0:] RoyalTSi[7894:562070] OpenPasswordDialog: starting PopModalAsync()
[0:]
[0:] RoyalTSi[7894:562070] System.NullReferenceException: Object reference not set to an instance of an object
at Xamarin.Forms.Platform.iOS.Platform.DidAppear () [0x0000d] in <filename unknown>:0
at Xamarin.Forms.Platform.iOS.PlatformRenderer.ViewDidAppear (Boolean animated) [0x00006] in <filename unknown>:0
at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, IntPtr principal, IntPtr delegate) [0x00005] in /Users/builder/data/lanes/1962/8b265d64/source/maccore/src/UIKit/UIApplication.cs:63
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/1962/8b265d64/source/maccore/src/UIKit/UIApplication.cs:47
at RoyalMobileApps.XF.iOS.Application.Main (System.String[] args) [0x00002] in d:\RoyalFamily\RoyalMobileApps.XF\iOS\RoyalTSi\Main.cs:19
As the text "starting PopModalAsync()" is there and "PopModalAsync() finished" is not, I do know, which line produced the exception even though the stack trace does not list it.
It looks like the method works, when I call it from the UI thread. But when I call it from a background thread, then it crashes. I tried with and without the ConfigureAwait on the GetValues call - no difference.
How do I have to write that method?