2

Using await client.GetAsync(uri) blocks my UI thread.

Here's the code inside my button click event handler:

private async void Button_Clicked(object sender, EventArgs e)
    {
        var vm = new MainPageViewModel();

        HttpClient client = new HttpClient();
        client.MaxResponseContentBufferSize = 256000;

        var uri = new Uri(string.Format("http://localhost:50715/api/values"));

        var response = await client.GetAsync(uri); // This is where UI gets blocked
        SongView.ItemsSource = new List<Song>();
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            vm.Songs = await Task.Factory.StartNew(() =>
            {
                return JsonConvert.DeserializeObject<List<Song>>(content);
            });
        }

        SongView.ItemsSource = vm.Songs;
    }

And even with just this code it still blocks the UI on the same line.

private async void Button_Clicked(object sender, EventArgs e)
    {
        HttpClient client = new HttpClient();
        client.MaxResponseContentBufferSize = 256000;

        var uri = new Uri(string.Format("http://localhost:50715/api/values"));

        var response = await client.GetAsync(uri); // This is where UI gets blocked
    }

Can you point out what I'm doing wrong?

6
  • Is that really just the code? You're getting a response from the server and doing nothing with it? Commented Jun 19, 2017 at 15:49
  • 3
    @Kharlan Can you post a reproducible example of the issue? The code provided does not block the UI thread. In your second sample how are you determining the UI thread is blocked, are you using an activity indicator? What is the purpose of setting the MaxResponseContentBufferSize in your code, especially in the second sample? Can you be more specific about the behavior you're seeing? Commented Jun 19, 2017 at 17:43
  • @JSteward I'm debugging on a UWP app running in Local Machine. When I click the button that calls this event handler, I an't move the window while it's loading. Commented Jun 20, 2017 at 3:30
  • @Paulo Morgado I'm using it to populate a list into a ListView. In my second example i'm just pointing out that the line that calls await client.GetAsync(uri) is blocking the UI Commented Jun 20, 2017 at 3:31
  • @JSteward You're right. My code does not block the UI. I tried debugging it on an android emulator. Probably the freeze that I see is being caused by visual studio while debugging a UWP app on Local Machine. Commented Jun 20, 2017 at 3:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.