C# Task.GetAwaiter and GetResult with Appication.OnExit(Window.Closing)
Lee, Cheul Woo
If you want to terminate with some System.Threading.Tasks.Task when your C# WPF app exits, you should use Task.GetAwaiter() and GetResult() instead of async/await. The appropriate termination event is Application.OnExit (or Window.Closing).
Create a .Net 9 WPF app project using Visual Studio 2022 Community.
Get Lee, Cheul Woo’s stories in your inbox
Join Medium for free to get updates from this writer.
Remove StartupUri=”MainWindow.xaml” from the App.xaml file.
<Application x:Class=”Study.Wpf.TestGetAwaiter.App”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local=”clr-namespace:Study.Wpf.TestGetAwaiter”>
<Application.Resources>
</Application.Resources>
</Application>
In App.xaml.cs, change the class App as shown below. Here, Task.Delay takes care of the terminiating(finishing) task.
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
AllocConsole();
Console.WriteLine(nameof(OnStartup));MainWindow = new MainWindow();
MainWindow.Show();
}protected override void OnExit(ExitEventArgs e)
{
Task.Delay(3000).GetAwaiter().GetResult();
Console.WriteLine(nameof(Task.Delay));
Console.ReadLine();Console.WriteLine(nameof(OnExit));
FreeConsole();
base.OnExit(e);
}[DllImport(“kernel32.dll”, SetLastError = true)]
public static extern bool AllocConsole();[DllImport(“kernel32.dll”, SetLastError = true)]
public static extern bool FreeConsole();
}
If you build this, run it, and exit, you’ll see that it outputs ‘Delay’(terminating) after 3 seconds.
protected override async void OnExit(ExitEventArgs e)
{
//Task.Delay(3000).GetAwaiter().GetResult();
await Task.Delay(3000).ConfigureAwait(false);
Console.WriteLine(nameof(Task.Delay));
Console.ReadLine();Console.WriteLine(nameof(OnExit));
FreeConsole();
base.OnExit(e);
}
Task.GetAwaiter() and GetResult(), which are usually avoided in asynchronous programs, play an important role in the above situation.






