await void任务(C#)

cra*_*atu 0 c# asynchronous async-await

在等待完成之前,我需要在运行空任务之后运行一些有用的代码.

样品:

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;
    });
}
Run Code Online (Sandbox Code Playgroud)

我知道如何在任务上写这个,但无法理解async/await.任何人都可以写工作样本.

谢谢.

Tit*_*mir 7

只需将处理程序声明为 async

private async void Button_Click(object sender, RoutedEventArgs e)
{
    Task t = SomeAsync();
    MessageBox.Show("before end");
    await t; 
    MessageBox.Show("after end");
}
Run Code Online (Sandbox Code Playgroud)

您应该考虑await t使用try.. catch未处理的错误,t因为应用程序未处理异常并将您的应用程序关闭.您可以Task使用TaskScheduler.UnobservedTaskException处理所有未观察到的异常,但是您应该阅读文档以了解它是否适​​合您的应用程序.