在Xamarin表单中调用DisplayALert()时获取异常

时间:2018-11-01 09:33:16

标签: xamarin.forms

我正在尝试使用以下代码以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;
        }
    }

异常详细信息: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]

请让我知道是否有人遇到过类似的问题

1 个答案:

答案 0 :(得分:3)

由于某种原因,您不是从UI线程调用此函数。

使用BeginInvokeOnMainThread方法包装呼叫

Device.BeginInvokeOnMainThread (async () => {
    await DisplayAlert("Alert", "You have been alerted", "OK");
});

当您在后台线程上做某事并且想要与UI交互时,您将需要BeginInvokeOnMainThread方法在负责UI的主线程上调用它。