编写异步单触引代码

nac*_*10f 4 .net asynchronous xamarin.ios task-parallel-library azure-mobile-services

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

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);
                                }
                            });             
                        }});
        }
Run Code Online (Sandbox Code Playgroud)

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

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

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

val*_*ero 16

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

InvokeOnMainThread(() => {  
    NavigationController.PushViewController (new TabBarController(), false);
});
Run Code Online (Sandbox Code Playgroud)

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

new NSObject().InvokeOnMainThread(() => {   
    NavigationController.PushViewController (new TabBarController(), false);
});
Run Code Online (Sandbox Code Playgroud)


hol*_*mes 8

看看InvokeOnMainThread或BeginInvokeOnMainThread

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

NavigationController.BeginInvokeOnMainThread (delegate { 
    NavigationController.PushViewController (new TabBarController (), false);
}); 
Run Code Online (Sandbox Code Playgroud)