我有一个使用 MahApps.Metro 的 WPF 应用程序,并带有一个标题栏关闭按钮来关闭该应用程序。我的目标是在应用程序关闭时将记录存储在 Azure 存储帐户中。我已经实现了在窗口关闭事件处理程序中将数据保存到 Azure 存储的逻辑。但是,我注意到应用程序退出时没有保存数据,并且没有抛出异常。我已确保事件处理程序已正确订阅,并且在保存过程中没有错误。我应该采取哪些步骤来诊断和解决此问题?任何见解或建议将不胜感激。
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
在关闭事件中处理代码有点棘手,但并非不可能。 您可以使用标志来存储关闭状态,执行您自己的代码,然后强制关闭窗口。
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();
}
希望有帮助。