Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a refresh button in my app that uses some async methods to update the list of items displayed. The problem is that I can't have a return type of Task for the event handler for the button click so I'm left with an async void method. Thus, the user can hit the refresh button, then select an item while the list is being repopulated which will result in an error.

start of code that handles button click:

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {


        await ViewModel.CreateMessageCommand();

So is there anyway to properly await for this task to finish?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
542 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since event handlers for controls typically return void, you need to handle this in a different manner. This often means, in a scenario like yours, that you need to disable all or part of your UI while things are loading, i.e.:

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    // Make the "list" disabled, so the user can't "select an item" and cause an error, etc
    DisableUI();

    try
    {    
       // Run your operation asynchronously
       await ViewModel.CreateMessageCommand();
    }
    finally
    {
       EnableUI(); // Re-enable everything after the above completes
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...