MAUI获取主线程Dispatcher报错:调用时机异常,主窗口未创建
问题:获取主线程Dispatcher时抛出InvalidOperationException错误
我尝试通过以下代码获取主线程的Dispatcher:
public partial class MainPage { public MainPage() { InitializeComponent(); } private async void OnButtonClicked(object sender, EventArgs e) { var disp = CoreApplication.MainView.CoreWindow.Dispatcher; } }
执行后抛出如下错误:
Exception thrown: 'System.InvalidOperationException' in WinRT.Runtime.dll WinRT information: Could not create a new view because the main window has not yet been created An exception of type 'System.InvalidOperationException' occurred in WinRT.Runtime.dll but was not handled in user code WinRT information: Could not create a new view because the main window has not yet been created A method was called at an unexpected time.
问题原因
- 主窗口CoreWindow未完成初始化:虽然代码是在按钮点击事件中调用,但在部分WinUI/UWP场景下,
CoreApplication.MainView对应的CoreWindow还未完全绑定到主线程的UI上下文,应用主窗口的初始化流程尚未完成就触发了该调用。 - 错误提示存在误导:错误信息里提到的"无法创建新视图因为主窗口尚未创建"并非实际问题,真实情况是你尝试访问的主窗口CoreWindow还未处于就绪状态,导致访问其Dispatcher时抛出异常。
内容的提问来源于stack exchange,提问作者yonutix
相关产品推荐
相关产品推荐

