[英]Xamarin Forms - Android Thread
我正在使用Xamarin Forms和MVC API .net实施Web API服务。 我已经创建了Auth服务,并且可以使用Postman应用获取访问令牌。 如果我在UWP平台上运行项目,则该应用程序可以正常运行,我可以让用户获得令牌来访问Web API。 但是,每当我在Android平台上运行该应用程序时,都会出现一个未处理的异常,即“跳过了36帧。该应用程序可能在其主线程上做过多的工作”。 我正在使用异步...等待方法,但仍然收到此错误。 您能告诉我如何避免此错误吗? 谢谢!
这是我的代码:
ApiServices:
public class ApiServices {
public async Task RegisterUserAsync(string email, string password, string confirmPassword) {
var client = new HttpClient();
var success = false;
var model = new RegisterBindingModel {
Email = email, Password = password, ConfirmPassword = confirmPassword
};
try {
var json = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if (email != null || password != null) {
success = true;
Acr.UserDialogs.UserDialogs.Instance.ShowSuccess(string.Format("You are now signed-in as {0}.", email));
var response = await client.PostAsync(Constants.BaseApiAddress + "api/Account/Register", content);
Debug.WriteLine(response);
Debug.WriteLine(await response.Content.ReadAsStringAsync());
Debug.WriteLine(response.StatusCode);
}
} catch (Exception ex) {
//Acr.UserDialogs.UserDialogs.Instance.ShowError(string.Format("Authentication Failed: {0}", ex.Message));
}
}
}
LoginViewModel:
public class LoginViewModel {
public string Email {
get;
set;
}
public string Password {
get;
set;
}
public ICommand LoginCommand {
get {
return new Command(async() => {
ApiServices apiServices = new ApiServices();
await apiServices.LoginUserAsync(Email, Password);
});
}
}
}
Async / await关键字提供异步支持,但是如果在UI线程中使用异步支持,则会损害性能。 因此,为了改善UI体验,请使用Task.Run()在另一个线程(如@SushiHangover)中执行代码。
LoginViewModel:
public class LoginViewModel {
public string Email {
get;
set;
}
public string Password {
get;
set;
}
public ICommand LoginCommand {
get {
return new Command(async() => {
ApiServices apiServices = new ApiServices();
await Task.Run(() => {
apiServices.LoginUserAsync(Email, Password);
});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.