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