我需要在 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/