Dispatcher在Textchanged事件中的Messagebox.Show上抛出InvalidOperationException

首先,这是我的错误的错误日志条目

crash program @ 15-9-2011 15:01:30error:System.InvalidOperationException: Dispatcher processing has been suspended, but messages are still being processed. at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

无论如何代码:

 private void TB_postcode_cijfers_TextChanged(object sender, TextChangedEventArgs e){ if (TB_postcode_cijfers.Text != string.Empty || TB_postcode_cijfers.Text.Length > 0) { LBL_postcode.Content = Postcode_cijfers + Postcode_letters; if (TB_postcode_cijfers.Text.Length == 4 && TB_postcode_letters.Text.Length == 2) { if (!ZoekOpPostcode(Injectioncheck(TB_postcode_cijfers.Text + TB_postcode_letters.Text))) { //MessageBox.Show("Geen resultaat gevonden, " + errortext); if (MessageBox.Show("Geen resultaat gevonden, " + errortext + ".\n Wilt u overschakelen naar handmatig? ", "Handmatig?", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { RB_handmatig.IsChecked = true; } else { // } } } }} 

所以在messagebox.show方法上。 这只有在用户将读取模式切换到我的表单上的编辑模式时才会发生。 这涉及折叠显示一些标签和ui控件。

如果事件从userinput触发,一切都很好。 我想知道的是:为什么隐藏和显示一些控件时,textchanged事件会触发。 我该怎么做才能防止这个错误?

编辑:上面的代码是在自定义的Wpf控件中。 放在winforms项目/表格中

看到这个线程,它描述了与你相同的问题:

例外是为了防止由于改变视觉树而导致的奇怪性引起的重入错误,而这种事件(它本身已被视觉树改变触发)正在发射。 如果你真的必须在UI元素的状态发生变化时确认一些事情,那么使用Dispatcher.BeginInvoke延迟可能是正确的做法。

要在UI线程上运行代码,请执行以下操作:

  Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { if (MessageBox.Show("Geen resultaat gevonden, " + errortext + ".\n Wilt u overschakelen naar handmatig? ", "Handmatig?", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { RB_handmatig.IsChecked = true; } else { // } }));