我正在尝试开发Windows应用程序并遇到问题。 我有一个MainPage.xaml和另外两个StartScreen.xaml和Player.xaml。 如果某些条件为真,我将切换MainPage的内容。 因此,我在StartScreen中有一个事件,它检查一个目录是否存在,但每次发生错误时都会抛出。在UI线程上执行同步操作
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分支一切都很好,但是当DIR可我收到以下错误信息:
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 = "";
}
});
}
仍是同样的错误,我的理解这应该是异步运行并等待代码完成,但它似乎并不如此。我也尝试了其他的东西,但仍然得到错误。 我不知道如何解决这个问题,有人可以解释为什么会发生这种情况,以及如何解决这个问题。