4

所以我有一个必须执行三个任务的方法。第一个任务必须在另外两个之前完成,可以并行执行。这就是我现在所拥有的(为简单起见进行了修改)

void facebookButtonClicked (object sender, EventArgs e)
        {
            View.Add (loadingOverlay);
            AppDelegate.MobileService = new MobileServiceClient ("myserverUrl", "myApiKey");
            var users= AppDelegate.MobileService.GetTable<User> ();
            var identities= AppDelegate.MobileService
                .GetTable ("Identities");
            AppDelegate.MobileService
                .LoginAsync (this, MobileServiceAuthenticationProvider.Facebook)
                    .ContinueWith (t => {
                if (t.Status == TaskStatus.RanToCompletion) {
                            AppDelegate.mobileServiceUser = t.Result;
                            var task1 = users.InsertAsync(new User{BirthDate = DateTime.Now});
                            var task2 = identities.ReadAsync("");
                            Task.Factory.ContinueWhenAll(new Task[]{task1,task2},_=>{
                                if(task1.Status==TaskStatus.RanToCompletion && task2.Status== TaskStatus.RanToCompletion)
                                {
                                    var token = task2.Result
                                        .GetArray()[0]
                                        .GetObject ()
                                        .GetNamedObject ("identities")
                                        .GetNamedObject ("facebook")
                                        .GetNamedString ("accessToken");    

                                SaveAuthorization (token);
                                NavigationController.PushViewController (new TabBarController (), false);
                                }
                            });             
                        }});
        }

问题是(除了我是异步代码的新手)当它尝试执行“PushViewController”时,我得到:

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

如何重构/修改此代码以修复它?请帮忙。

4

2 回答 2

16

我调用 InvokeOnMainThread 并在我的异步方法中使用匿名函数。

InvokeOnMainThread(() => {  
    NavigationController.PushViewController (new TabBarController(), false);
});

如果由于某种原因你在一个静态类中(就像我一样),你可以这样做

new NSObject().InvokeOnMainThread(() => {   
    NavigationController.PushViewController (new TabBarController(), false);
});
于 2012-12-06T21:23:57.130 回答
8

看看 InvokeOnMainThread 或 BeginInvokeOnMainThread

http://docs.xamarin.com/ios/Guides/Advanced_Topics/Threading#Developing_Responsive_Applications

NavigationController.BeginInvokeOnMainThread (delegate { 
    NavigationController.PushViewController (new TabBarController (), false);
}); 
于 2012-12-06T21:07:10.953 回答