Reputation: 64
I need to run some useful code after run an empty task before await for it finish.
sample:
private void Button_Click(object sender, RoutedEventArgs e)
{
Task t = SomeAsync();
MessageBox.Show("before end");
await t; // <-- how to write this?
MessageBox.Show("after end");
}
private async Task SomeAsync()
{
await Task.Run(() =>
{
//do some work;
});
}
I know how to write this on tasks but can't understand async/await. Can anyone write working sampe.
Thanks.
Upvotes: 0
Views: 153
Reputation: 250366
Just declare the handler as async
private async void Button_Click(object sender, RoutedEventArgs e)
{
Task t = SomeAsync();
MessageBox.Show("before end");
await t;
MessageBox.Show("after end");
}
You should consider surrounding await t
with a try.. catch
as unhandled errors in t
will bubble up as application un handled exceptions and bring down you application. You can handle all unobserved Task
exceptions using TaskScheduler.UnobservedTaskException but you should read the documentation to see if this is suitable for your application.
Upvotes: 7