3

有一个很难重现的问题。
例外是:

e.Exception.Message = Object reference not set to an instance of an object.
e.Exception.StackTrace 
at System.Windows.Controls.ItemContainerGenerator.MoveToPosition(GeneratorPosition position, GeneratorDirection direction, Boolean allowStartAtRealizedItem, GeneratorState& state)
at System.Windows.Controls.ItemContainerGenerator.Generator..ctor(ItemContainerGenerator factory, GeneratorPosition position, GeneratorDirection direction, Boolean allowStartAtRealizedItem)

我在 App.cs App_DispatcherUnhandledException 中发现了这一点

我认为这来自 XAML,因为我为 Visual Studio 中的每个选项都打开了 Break on Thrown。
而且我很确定我已经将所有代码都包含在 Try Catch 中。
可以肯定的是,我认为错误源自的页面正在捕获异常背后的所有代码。
如果我在获取这些公共属性时中断,我将无法重现该错误。
当我放慢速度尝试调试时,就很难重现。

有一些选项卡,我使用 TextBlock 显示文本并使用 FlowDocumentViewer 显示格式化文本。

源绑定到公共属性。TextBlock.Text 的公共属性是 RawText,支持变量是 rawText。

我获取文本和信息以格式化在 UI 线程上创建的 BackgroundWorker 上的文本。
在调用 BackgroundWorker 之前,我将 rawText 设置为“获取文本”并在 BackgroundWorker IsBusy 时调用 CancelAsync()。
然后在 RunWorkerCompletedEventHandler 上,我将 rawText 设置为实际文本。然后,如果选择了该选项卡,我只会调用 notifypropertychanged ,因此如果它不可见,则不会呈现。

问题可能是我在控件读取 rawText 时更改 RunWorkerCompletedEventHandler 中的 rawText 吗?或者我在 UI 控件读取文本时将 rawText 更改为“获取文本”?

还有其他想法?

对这些作业加锁会解决这个问题吗?

不是 MVVM。

我以为我充分描述了代码,但显然没有。

rawText = "getting text";
backgroundWorker.RunWorkerAsync(input);

然后在 RunWorkerCompleted

DocTextAndHighlight docTextAndHighlight = (GabeLib.DocTextAndHighlight)e.Result;
rawText = docTextAndHighlight.RawText;

仅当该选项卡打开时,才会调用 RawText 上的 NotifyPropertyChanged。

添加了锁并且无法重现错误,但这并不意味着它已经消失了。
必须在生产中进行测试。
还添加了直通转换到我怀疑的控件并写出调试消息。
我不知道是什么引发了异常,而异常什么也没告诉我。

这可能是一个带有 DDE 接口的旧 com 组件。
一个方法调用报告了这个完全相同的错误。
这是一个方法调用,只有万分之一失败。
但是,如果它失败了,它将在块中失败。
并且该调用位于 try catch 块中,但由于某种原因,它没有被直接块捕获。授予该错误的信息很少,但它是完全相同的错误。不好的部分是它会使应用程序崩溃。
我可以设置 e.Handled = true; 但它仍然会引发足够多的错误以使应用程序崩溃。

4

1 回答 1

2

DoWork 将在线程池线程上运行,而 RunWorkerCompleted 将在 UI 线程上运行,前提是您的 BackgroundWorker 是在 UI 线程上创建的。

并来自 MSDN:

在访问 RunWorkerCompletedEventArgs.Result 属性之前,您的 RunWorkerCompleted 事件处理程序应始终检查 AsyncCompletedEventArgs.Error 和 AsyncCompletedEventArgs.Cancelled 属性。如果引发异常或操作被取消,访问 RunWorkerCompletedEventArgs.Result 属性会引发异常。( http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx ):

于 2013-09-15T03:00:22.047 回答