Cleve Cleve - 4 months ago 20
C# Question

How to avoid awaiting a task in an event handler that isn’t a ‘top level’ one?

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();

Many thanks in advance.


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;
    await showProgressTask;