我遵循一种相当常见的模式来使用异步对话框方法确认/取消我的主窗口关闭。但是,在我调用来呈现对话框的异步任务中,在某些情况下,我立即返回布尔值,而不是等待对话框任务方法的返回。在这些情况下,会引发异常:
System.InvalidOperationException:“无法在窗口关闭时将“可见性”设置为“可见”或调用Show,ShowDialog,Close或WindowInteropHelper.EnsureHandle。”
似乎这是因为异步任务正在同步返回并在窗口上调用Close(),而不是将其余代码作为继续。除了将try(catch)中包装Close()或在返回布尔值之前在函数中添加Task.Delay()之外,还可以检测是否应该在窗口上调用Close()吗? (即,如果任务同步返回)
或者...我在概念上是否缺少异步/等待模式中的某些内容?
这是我的代码:
private bool _closeConfirmed;
private async void MainWindow_OnClosing(object sender,CancelEventArgs e)
{
//check if flag set
if(!_closeConfirmed)
{
//use flag and always cancel first closing event (in order to allow making OnClosing work as as an async function)
e.Cancel = true;
var cancelClose = await mainViewModel.ShouldCancelClose();
if(!cancelClose)
{
_closeConfirmed = true;
this.Close();
}
}
}
这是异步函数的样子:
public async Task<bool> ShouldCancelClose()
{
if(something)
{
var canExit = await (CurrentMainViewModel as AnalysisViewModel).TryExit();
if (!canExit) //if user cancels exit
return true;
//no exception
return false;
}
//this causes exception
return false;
}