0

I try to lean Xamarin. I created a simple test application.

MainPage.xaml.cs

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    string apiBaseUri = "192.168.0.155/RestfulAPI";

    private async void OnButtonClicked(object sender, System.EventArgs e)
    {
        var task = GetAPIToken(loginEntry.Text, passwordEntry.Text, apiBaseUri);
        var token = await task;
    }

    private static async Task<string> GetAPIToken(string userName, string password,
        string apiBaseUri)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new
            MediaTypeWithQualityHeaderValue("application/json"));
            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("password", password),
            });

            var responseMessage = await client.PostAsync(apiBaseUri + "/Token", formContent);
            var responseJson = await responseMessage.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(responseJson);
            return jObject.GetValue("access_token").ToString();
        }
    }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:GoodWill_Mobile"
             x:Class="GoodWill_Mobile.MainPage">
    <ContentPage.Content>
        <StackLayout>
            <Entry x:Name="loginEntry"/>
            <Entry x:Name="passwordEntry"
                   Placeholder="Password"
                   IsPassword="True" />
            <Button Text = "Нажми!"
                    FontSize="Large"
                    BorderWidth="1"
                    HorizontalOptions="Center"
                    VerticalOptions="CenterAndExpand"
                    Clicked="OnButtonClicked" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

But it failed with error: Skipped 477 frames! The application may be doing too much work on its main thread.

As I read I cause by UI blocking. But I make operation async and not understant why I still get this error.

PoLáKoSz
  • 355
  • 1
  • 6
  • 7
Oleg Volkov
  • 189
  • 4
  • 15
  • Possible duplicate of [Why is an async method with await keyword still blocking the main thread?](https://stackoverflow.com/questions/43841542/why-is-an-async-method-with-await-keyword-still-blocking-the-main-thread) – Trevor Balcom Nov 17 '17 at 20:48
  • 1
    This not helped. Still not work. – Oleg Volkov Nov 19 '17 at 21:38

0 Answers0