c# - 异步方法?

标签 c# multithreading xamarin.ios

我需要在 Monotouch 中异步进行 Web 服务调用,因为 UIAlertView 仅在工作完成后才会显示。

当前代码(伪)

Class LoginviewController
{
        void Login(credentials)  
        {  
            showAlert("Logging in") ;   
            bool authenticated = service.Authenticate(Credentials);  
        }
 }       

 class Service
 {
       Public bool Authenticate(object Credentials)
       {
          object[] results = this.Invoke("GetAuth", Credentials)
       }
 }

我正在将 Service 方法转移到异步模型,Authenticate 由 BeginAuthenticate()、EndAuthenticate()、AuthenticateAsync()、OnAuthenticateOperationCompleted() 组成,当然验证()

当所有这些完成后,我需要在 LoginViewController 上运行 OnAuthenticateCompleted(),因此我将使用 BeginInvokeOnMainThread(delegate....

这就是我陷入困境的地方。

如何获取从服务类执行的 LoginViewController 类实例中的方法 OnAuthenticateCompleted()

编辑:解决方案:

添加了一个在 Login() 中连接的 OnAuthenticateCompleted 事件处理程序,并调用 AuthenticateAsync() 方法而不是 Authenticate()。

Class LoginviewController
    {
            void Login(credentials)  
            {  
                showAlert("Logging in") ;   
                service.AuthenticateCompleted += new GetAuthenticationCompletedEventHandler(OnAuthenticateCompleted);
                service.AuthenticateAsync(Credentials);  
            }

            public void OnAuthenticateCompleted(obj sender, GetAuthenticationCompletedEventArgs args)
            {
                bool authenticated = (bool)args.Results;
                //do stuff
                hideAlert();
            }
     }     

最佳答案

您不会从服务类执行 LoginViewController.OnAuthenticateCompleted,而是在已完成的事件处理程序中执行它。

class LoginViewController
{
    void Login (credentials)
    {
        service.AuthenticateAsync (credentials, LoginCompletedCallback);
        }

    }
    void LoginCompletedCallback ()
    {
        BeginInvokeOnMainThread (OnAuthenticateCompleteded);
    }
}

关于c# - 异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13116816/

相关文章:

c# - DryIoc 递归依赖异常与工厂(Func<>)

Java isAlive() 和 join()

c# - 带有自定义 PIN 图像的 MonoTouch Multiple Mapkit CLLocationCooperative2D

c# - lock(syncRoot) 对静态方法有何意义?

C++ 线程级常量

c# - Xamarin 需要引用 Windows.Foundation.FoundationContract

c# - 将文本字段添加到 UIAlertView

c# - 如何将二进制转换为十进制

c# - Json.net反序列化null guid案例

c# - 如何在 Entity Framework Code-First 中创建自定义 m2m 表