MAUI应用关闭第二窗口后调用DisplayAlert抛出COMException求助
问题:MAUI中关闭第二窗口后调用DisplayAlert抛出COM异常
MAUI应用里,添加新客户端后原本会正常弹出添加成功的提示。但打开并关闭显示客户端信息的第二窗口后,再次添加新客户端时,虽然数据已经成功写入数据库,但调用DisplayAlert时会抛出异常。
异常信息
Exception thrown: 'System.Runtime.InteropServices.COMException' in WinRT.Runtime.dll WinRT information: The WinUI Desktop Window object has already been closed. Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Private.CoreLib.dll WinRT information: The WinUI Desktop Window object has already been closed. The program '[77340] VetOrg.exe' has exited with code 3221226107 (0xc000027b).
相关代码
打开第二窗口的代码
public async void GetOwnerInfo() { Window window = new Window(new ClientView(new ClientViewModel(db, SelectedOwner))); Application.Current.OpenWindow(window); }
调用DisplayAlert的代码
await App.Current.MainPage.DisplayAlert("Done", AppRes.DoneOwnerPetComplaint, AppRes.Ok);
原因及解决办法
问题核心是关闭第二窗口后,App.Current.MainPage的上下文可能被已关闭的窗口污染,导致调用弹窗时关联到了无效的窗口对象。
方案1:使用当前活跃窗口的Page调用弹窗
放弃直接依赖App.Current.MainPage,改为获取当前处于活跃状态的窗口来调用DisplayAlert:
var activeWindow = Application.Current.Windows.FirstOrDefault(w => w.IsActive); if (activeWindow?.Page != null) { await activeWindow.Page.DisplayAlert("Done", AppRes.DoneOwnerPetComplaint, AppRes.Ok); }
方案2:修正窗口打开的异步写法
将async void改为async Task(避免异步无返回值带来的上下文泄漏),并使用MAUI推荐的异步窗口打开方法:
public async Task GetOwnerInfo() { var newWindow = new Window(new ClientView(new ClientViewModel(db, SelectedOwner))); await Application.Current.OpenWindowAsync(newWindow); }
方案3:直接绑定主窗口调用弹窗
明确指定使用应用主窗口的Page来调用弹窗,确保上下文正确:
var mainWindow = Application.Current.MainWindow; if (mainWindow != null && mainWindow.IsActive && mainWindow.Page != null) { await mainWindow.Page.DisplayAlert("Done", AppRes.DoneOwnerPetComplaint, AppRes.Ok); }
内容的提问来源于stack exchange,提问作者Ibrahim Salama
相关产品推荐
相关产品推荐

