Reputation: 41
I have a WPF application using MahApps.Metro with a title bar closure button to close the application. My goal is to store records in an Azure Storage Account when the application closes. I've implemented logic to save the data to Azure Storage within the window closing event handler. However, I've noticed that the application exits without saving the data, and no exceptions are being thrown. I've ensured that the event handler is properly subscribed to and that there are no errors during the saving process. What steps should I take to diagnose and resolve this issue? Any insights or suggestions would be appreciated.
public partial class MainWindow : MetroWindow
{
connString ="azure storage account key";
public MainWindow()
{
InitializeComponent();
Closing += MainWindow_Closing;
}
private async void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
await DataService.SaveData(connString, userId);
}
catch (Exception ex)
{
throw new Exception($"An error occurred while saving userId: {ex.Message}");
}
}
}
DataService :
TableClient connClient = new TableClient(connString, MytableName);
await connClient.CreateIfNotExistsAsync() // Application closing here without any error
Upvotes: 0
Views: 55
Reputation: 14611
Handling code in a closing event is a little bit tricky but not impossible. You can use a flag to store the closing state, execute your own code and after that force closing the window.
private bool forceClose = false;
private void CloseForced()
{
// Closing main window
this.forceClose = true;
this.Close();
}
private async void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// force method to abort - we'll force a close explicitly
e.Cancel = true;
if (this.forceClose)
{
// cleanup code already ran - shut down
e.Cancel = false;
return;
}
// execute shutdown logic
try
{
await DataService.SaveData(connString, userId);
}
catch (Exception ex)
{
throw new Exception($"An error occurred while saving userId: {ex.Message}");
return;
}
// explicitly force the window to close
this.CloseForced();
}
Hope that helps.
Upvotes: 1