我尝试使用以下代码在 xamarin 表单中启动警报框,但调用失败并出现以下异常。
private async void ProfileEmailAddressViewModel_UpdatedPersonalDetailsEvent(object source, UpdateEmployeePersonalDetailsCompletedEventArgs e)
{
try
{
if (e.Result)
{
await DisplayAlert("Alert", "You have been alerted", "OK");
}
}
catch (Exception ex)
{
throw ex;
}
}
Run Code Online (Sandbox Code Playgroud)
异常详细信息:System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> UIKit.UIKitThreadAccessException: UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread.
at UIKit.UIApplication.EnsureUIThread () [0x0001a] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/UIKit/UIApplication.cs:88
at UIKit.UIView.set_BackgroundColor (UIKit.UIColor value) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/UIKit/UIView.g.cs:2817
at Xamarin.Forms.Platform.iOS.Platform.PresentAlert (Xamarin.Forms.Internals.AlertArguments arguments) [0x0000d]
如果有人遇到类似问题,请告诉我
由于某种原因,您没有从 UI 线程调用它。
将调用包装在BeginInvokeOnMainThread方法中
Device.BeginInvokeOnMainThread (async () => {
await DisplayAlert("Alert", "You have been alerted", "OK");
});
Run Code Online (Sandbox Code Playgroud)
当您在后台线程上执行某些操作并且想要与 UI 交互时,您将需要BeginInvokeOnMainThread在负责 UI 的主线程上调用它的方法。