Cleve Cleve - 1 year ago 71
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download