在Ui线程上执行同步操作

2023-11-29

我正在尝试开发 Windows 应用程序并遇到问题。 我有一个 MainPage.xaml 和另外 2 个 StartScreen.xaml 和 Player.xaml。 如果某些条件成立,我将切换主页的内容。 因此,我在 StartScreen 中有一个事件,它检查目录是否存在,但每次出现错误时都会抛出错误。

private void GoToPlayer_Click(object sender, RoutedEventArgs e)
    {

        if (Directory.Exists(this.main.workingDir + "/" + IDText.Text + "/Tracks")) // Error occurs here
        {
            this.main.Content = this.main.player; //here i switch between different ui forms
        }
        else
        {
            MessageBox.Text = "CD not found";
            IDText.Text = "";
        }

    }

当它到达 else 分支时,一切都很好,但是当目录可用时,我收到以下错误消息:

An exception of type 'System.InvalidOperationException' occurred in System.IO.FileSystem.dll but was not handled in user code

附加信息:不应在 UI 线程上执行同步操作。考虑将此方法包装在 Task.Run 中。

即使我在 if 分支中注释代码,错误仍然出现。

我试过这个:

private async void GoToPlayer_Click(object sender, RoutedEventArgs e)
    {
        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
            if (Directory.Exists(this.main.workingDir + "/" + IDText.Text + "/Tracks")) // Error occurs here
            {
                this.main.Content = this.main.player; //here i switch between different ui forms
            }
            else
            {
                MessageBox.Text = "CD not found";
                IDText.Text = "";
            }
        });
    }

仍然是同样的错误,据我了解,这应该异步运行并等待代码完成,但似乎并非如此。我还尝试了其他一些东西,但仍然出现错误。 我不知道如何解决这个问题,有人可以解释一下为什么会发生这种情况以及如何解决这个问题。


正如例外情况所示,您不能调用Directory.Exists在 UI 线程中同步。将整个代码块放入 Dispatcher 操作中仍然会在 UI 线程中调用它。

在 UWP 应用中,您通常会使用StorageFolder.TryGetItemAsync检查文件或文件夹是否存在的方法:

private async void GoToPlayer_Click(object sender, RoutedEventArgs e)
{
    var folder = await StorageFolder.GetFolderFromPathAsync(main.workingDir);

    if ((folder = await folder.TryGetItemAsync(IDText.Text) as StorageFolder) != null &&
        (folder = await folder.TryGetItemAsync("Tracks") as StorageFolder) != null)
    {
        ...
    }
}

请注意,您可能仍然会收到UnauthorizedAccessException当应用程序不允许访问时main.workingDir.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Ui线程上执行同步操作 的相关文章

随机推荐