Is it possible to await async tasks during a button click?

折月煮酒 提交于 2019-12-18 03:09:12

问题


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?


回答1:


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
    }
}



回答2:


You should simply disable all of the UI controls that the user shouldn't be interacting with at the start of the action, and then enable them at the end.




回答3:


One way would be to wrap the View in a BusyIndicator from the WPF Toolkit

You would provide a bool property on your viewmodel and toggle the value at the start and end.

It puts up a UI element above all the other controls preventing user interaction but providing an animated busy message, which can be updated to say whatever you wish.



来源:https://stackoverflow.com/questions/17792745/is-it-possible-to-await-async-tasks-during-a-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!