17

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?

Orch
  • 887
  • 2
  • 8
  • 21

3 Answers3

25

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
    }
}
Marcus Mangelsdorf
  • 2,852
  • 1
  • 30
  • 40
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
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.

Servy
  • 202,030
  • 26
  • 332
  • 449
1

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
ywm
  • 1,107
  • 10
  • 14
  • I don't see why it shouldn't. Unless they restrict what 3rd part libraries you can use. – ywm Jul 22 '13 at 16:52
  • 2
    You can't use WPF controls in Windows Store apps. Different platform, though still Xaml. You'd need a 3rd party busy indicator port (or write your own) – Reed Copsey Jul 22 '13 at 16:57
  • @ReedCopsey Since it is open source, you could download the source and recompile for the correct platform. Or only take the relevant BusyIndicator Control. – ywm Jul 23 '13 at 09:16
  • @ywm Unfortunately, moving from WPF to Windows Store is typically far more than a recompile. The Windows Store API is far less feature rich than WPF's, so depending on what's used in the control, it may be difficult. The version from the Silverlight Toolkit would likely be a far simpler port: https://silverlight.codeplex.com/SourceControl/latest#Release/Silverlight4/Source/Controls.Toolkit/BusyIndicator/BusyIndicator.xaml – Reed Copsey Jul 23 '13 at 16:23