I have to call an API when my WPF Applications is being closed.
I'm using Application_Exit
event because I have to do this even closing all the windows, being shut down from Task Manager or Alt + F4.
I've tried several ways, but all the options has some issues (some of them are these):
OPTION A: Async event + await
private async void Application_Exit(object sender, ExitEventArgs e)
{
if (MonitorInstance.Instance.User != null)
{
Log.Information($"Disconnect starting");
var result = await _apiClient.Disconnect();
Log.Information($"Disconnect result: {result}");
}
}
This option just calls the HTTP CONNECT (which sometimes succeed and others is being cancelled) but not my PATCH request.
OPTION B: Blocking Thread with Result
of Task.
private void Application_Exit(object sender, ExitEventArgs e)
{
if (MonitorInstance.Instance.User != null)
{
Log.Information($"Disconnect starting");
var result = _apiClient.Disconnect().Result;
Log.Information($"Disconnect result: {result}");
}
}
This effectively calls the API but the process continues running. Visual Studio continues showing that the App is running and this is not desired.
I think it's worth to mention that I'm calling the API (which uses SSL) using HttpClient
which is being created in the Disconnect
method and I'm using .NET Core 3.1.
My questions:
- Is
Application_Exit
the proper event to do this? - How to program the
Application_Exit
event to fulfill all the scenarios? - Should I change the implementation for my call to do it directly without the
HttpClient
?