3
private async void ProgressDialog_Opened(ContentDialog sender, ContentDialogOpenedEventArgs args)
{
    ProgressDialog p = sender as ProgressDialog;
    await DoCopyingAsync(p);
}

I’m aware that bad things happen when awaiting in async void methods, so how could I change my code is avoid this? This isn’t a ‘top level event handler’, where awaiting is 'permissible', but it gets fired after a call to

await progressDialog.ShowAsync();
halfer
  • 19,824
  • 17
  • 99
  • 186
Cleve
  • 1,273
  • 1
  • 13
  • 26
  • It's okay to await in event handlers. See this, for example: http://stackoverflow.com/a/19415703/2704659 – rory.ap Sep 29 '16 at 15:39
  • may be this not the question?!! – BRAHIM Kamel Sep 29 '16 at 15:40
  • 1
    @rory.ap It's not okay to await in event handlers *in general*. That only applies when you have a synchronization context and a good idea of how all of that works. It's just that in WinForms all of this is handled by the WinForms synchronization context, so it's usually safe to await in UI events on a WinForms thread. – Luaan Sep 29 '16 at 16:09

1 Answers1

2

I think the progress dialog should not be in charge of the copying, and the copying should not know anything about the progress dialog.

async void StartCopy_Click(object sender, RoutedEventArgs e)
{
    var progressDialog = new ProgressDialog();
    var progress = new Progress<int>(percent => progressDialog.Percent = percent);
    Task copyTask = DoCopyingAsync(progress);
    Task showProgressTask = progressDialog.ShowAsync();
    await copyTask;
    progressDialog.Hide();
    await showProgressTask;
}
piedar
  • 2,599
  • 1
  • 25
  • 37
  • Hi @piedar, really like the idea here. I've amended my code to reflect your suggestions but sadly the ProgressDialog just hangs as if the code is in deadlock. Here is the code I am using: ProgressDialog progressDialog = new ProgressDialog(); var progress = new Progress(percent => progressDialog.Percent = percent); await Task.WhenAll(progressDialog.ShowAsync().AsTask(), DoCopying(progress, storageFiles)); progressDialog.Hide(); – Cleve Sep 29 '16 at 17:25
  • Even if I change the DoCopying implementation to just await Task.Delay(..) it still hangs so it can't be that. – Cleve Sep 29 '16 at 17:28
  • Ok, I've fixed the hang by calling progressDialog.Hide within DoCopying so this makes ShowAsync complete. – Cleve Sep 29 '16 at 17:50
  • @Cleve Aha, I updated the answer to avoid that deadlock. – piedar Sep 29 '16 at 18:39
  • @ piedar thanks for your help. Appreciate the edited version which keeps me from having to pass in the progressDialog to DoCopyingAsync(). – Cleve Sep 29 '16 at 19:44