UIKit.UIKitThreadAccessException:UIKit一致性错误:您正在调用只能从UI线程调用的UIKit方法

时间:2019-03-29 18:53:23

标签: xamarin xamarin.forms xamarin.ios xamarin-forms-4

我正在尝试运行以下代码:

GetRepsButton.Command = new Command(async () =>
            {
                var url = @"https://url";

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //crashes here
                var test = await client.GetStringAsync(url);
            });

当我这样做时,整个应用程序崩溃,并且输出窗口显示此错误:

ROR: +[MSWrapperLogger MSWrapperLog:tag:level:]/7 Unhandled Exception:
UIKit.UIKitThreadAccessException: UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread.
  at UIKit.UIApplication.EnsureUIThread () [0x00020] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.6.0.16/src/Xamarin.iOS/UIKit/UIApplication.cs:89 
  at UIKit.UIGestureRecognizer.RemoveTarget (Foundation.NSObject target, System.IntPtr action) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.6.0.16/src/Xamarin.iOS/UIKit/UIGestureRecognizer.g.cs:342 
  at UIKit.UIGestureRecognizer.OnDispose () [0x00016] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.6.0.16/src/Xamarin.iOS/UIKit/UIGestureRecognizer.cs:41 
  at UIKit.UIGestureRecognizer.Dispose (System.Boolean disposing) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.6.0.16/src/Xamarin.iOS/UIKit/UIGestureRecognizer.g.cs:959 
  at
 Foundation.NSObject.Finalize () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.6.0.16/src/Xamarin.iOS/Foundation/NSObject2.cs:143 
Resolved pending breakpoint at 'SelectRep.xaml.cs:110,1' to void NameSpace.<ClientPicker_SelectedIndexChanged1>d__3.MoveNext () [0x0000c].

尽管我不认为必须这样做,因为我不使用UI进行任何操作,但我尝试了InvokeOnMainThread,该方法不起作用。我还尝试将其更改为.Result而不是等待,并且尝试了GetAsync并读取内容,以及使用WebClient而不是HttpClient。都导致相同的错误。

有什么想法吗?我正在使用Xamarin Forms 4 pre 7。

1 个答案:

答案 0 :(得分:1)

使用Device.BeginInvokeOnMainThread

Device.BeginInvokeOnMainThread(() =>
{
  //your code
});

https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.device.begininvokeonmainthread?view=xamarin-forms