簡體   English   中英

Xamarin表單-Android線程

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM