0

I created an asp.net web api. It works superbly, tested with postman. I would like to display the users on the wpf datagrid. The code is as follows:

    public partial class ListUsers : Page
{
    public ListUsers()
    {
        InitializeComponent();
        GetData();

    }

    public void GetData()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:1234/");

        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("api/users").Result;

        if (response.IsSuccessStatusCode)
        {
            var users = response.Content.ReadAsAsync<IEnumerable<Users>>().Result;

            UserGrid.ItemsSource = users;

        }
        else
        {
            MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
        }
    }
}

But unfortunately they appear very slowly on the data. For a moment the frost off the application. How to accelerate?

Sorry for the bad english.

1 Answers1

0

Make your method async:

public async Task GetData()

and await the server's response:

var users = await response.Content.ReadAsAsync<IEnumerable<Users>>();

(It's very rare that you actually ever want to call .Result directly.)

This will allow the application host to return control to the UI while awaiting the I/O operation in the background.

David
  • 176,566
  • 33
  • 178
  • 245
  • and how to call GetData method in ListUsers() ? –  Mar 25 '17 at 15:57
  • @mrnn: Short answer is "you don't". Performing I/O in a constructor is generally a bad idea. There's a lot more information here: http://stackoverflow.com/questions/23048285/call-asynchronous-method-in-constructor – David Mar 25 '17 at 15:58