Concurrently awaiting multiple asynchronous calls with independent continuations

前端 未结 4 984
时光说笑
时光说笑 2021-01-06 14:11

There are several scenarios where I need to invoke multiple asynchronous calls (from the same event handler) that can proceed independently of each other, with each one havi

4条回答
  •  执念已碎
    2021-01-06 14:36

    As I understand it, you need to query three async resources and only update the UI once all three have returned. If that's correct the Task.WhenAll control is idea to use. Something like

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        string nametext = null;
        string citytext = null;
        string ranktext = null;
    
        await Task.WhenAll(
            async () => nametext = await GetNameAsync(),
            async () => citytext = await GetCityAsync(),
            async () => ranktext = await GetRankAsync()
        );
    
        nameTextBox.Text = nametext;
        nameCityBox.Text = citytext;
        nameRankBox.Text = ranktext;
    }
    

提交回复
热议问题