我正在try 通过以下方式获取主线程的调度器:

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.

这可能是什么问题?

推荐答案

在WinUI3中,您应该使用DispatcherQueue.

这是一个基于默认毛伊岛项目的示例:

MainPage.xaml.cs

namespace MauiApp1;

public partial class MainPage : ContentPage
{
    int count = 0;

    public MainPage()
    {
        InitializeComponent();
    }

    private void OnCounterClicked(object sender, EventArgs e)
    {
        count++;

        if (count == 1)
            CounterBtn.Text = $"Clicked {count} time";
        else
            CounterBtn.Text = $"Clicked {count} times";

        SemanticScreenReader.Announce(CounterBtn.Text);
    }

    private Microsoft.UI.Dispatching.DispatcherQueue? _dispatcherQueue;

    private async void OnAsyncClicked(object sender, EventArgs e)
    {
        _dispatcherQueue ??= Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

        await Task.Run(async () =>
        {
            while (true)
            {
                count++;
                
                _dispatcherQueue.TryEnqueue(() =>
                {
                    CounterBtn.Text = $"Clicked {count} times";
                    SemanticScreenReader.Announce(CounterBtn.Text);
                });

                await Task.Delay(1000);
            }
        });
    }
}

Csharp相关问答推荐

使用变量子根名称在C#中重新初始化SON文件

Unity如何在PlayerPrefs中保存数据?

有没有一种方法可以防止在编译时在MicrosoftC或非单线程上下文中调用方法?

如何使用ConcurentDictionary属性上的属性将自定义System.Text.Json JsonConverter应用于该属性的值?

NumPy s fftn in C#with pythonnet'

发布用于Linux Ubuntu的C#应用程序

C#EF Core WHERE IN LINQ FROM LIST WITH.CONTAINS不返回任何内容

如何在实体框架中添加包含列表?

获取具有AutoFaces的所有IOptions对象的集合

为什么我可以用硬编码的集合而不是变量来设置没有setter的IList属性的值?

为什么方法的值在SELECT方法中不会更改?

在字符串C#之前获取数字

WPF DataGrid文件名列,允许直接输入文本或通过对话框按键浏览

为什么我的用户界面对象移动到略低于实际目标?

在.NET8中如何反序列化为私有字段?

错误:此版本的Visual Studio无法打开以下项目

C#Microsoft.CodeAnalysis.CSharp.Scriiting不等待并行.对于

C#静态抽象属性不能被子接口覆盖

如何在Cake脚本中设置MSBuild.exe的绝对路径

.NET EF Core Automapper项目到筛选不起作用