Calling async method on button click

前端 未结 3 1991
故里飘歌
故里飘歌 2020-12-01 03:38

I created Windows Phone 8.1 project and I am trying to run async method GetResponse(string url) on button click and waiting for the method to finish, but method is never fin

3条回答
  •  醉话见心
    2020-12-01 03:58

    This is what's killing you:

    task.Wait();
    

    That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...

    There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:

    private async void Button_Click(object sender, RoutedEventArgs 
    {
        Task> task = GetResponse("my url");
        var items = await task;
        // Presumably use items here
    }
    

    Or just:

    private async void Button_Click(object sender, RoutedEventArgs 
    {
        var items = await GetResponse("my url");
        // Presumably use items here
    }
    

    Now instead of blocking until the task has completed, the Button_Click method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)

    Note that I would also rename GetResponse to GetResponseAsync for clarity.

提交回复
热议问题