嗨 我通过数据库进行搜索.搜索在单独的线程中进行.找到实体后,我必须将其和一些相关数据显示到WPF UI中. 我使用EntityFramework.搜索过程的主要思想是:
Hi I have a search through database. Search works in separate thread. When entity is found I have to show it and some of related data into WPF UI. I use EntityFramework. Main idea of search process is:
foreach (var item in _currentEntitySet) { Items.Add(item); OnItemFound(item); }其中_currentEntitySet是一个ObjectQuery 但是我遇到了一些问题.触发OnItemFound时,我尝试使用BeginInvoke()在UI中显示找到的项目和一些相关对象.
Where _currentEntitySet is an ObjectQuery But I have met some problems. When OnItemFound is fired, I try to use BeginInvoke() to display found item and some related object in UI.
private void OnCatalogueItemFound(CatalogueItem item) { Application.Current.Dispatcher.BeginInvoke(new Action<object>((param) => { var model = new CatalogueResultItemViewModel(param as CatalogueItem); TitlesResultViewModel.Add(model); }), System.Windows.Threading.DispatcherPriority.Background, item); }问题在于项目的导航属性为NULL 当我使用Invoke()而不是BeginInvoke()时,一切正常.由于其他一些原因,我必须完全使用BeginInvoke(). 有谁知道在我的情况下如何使用BeginInvoke()?谢谢:)
The problem is that navigation properties of item are NULL When I use Invoke() instead of BeginInvoke() then things works fine. I have to use exactly BeginInvoke() because of some other reasons. Does anyone knows how can I use BeginInvoke() in my situation? Thanks :)
推荐答案请参阅Mark的评论和我对问题的评论. 您只需要了解Invoke和BeginInvoke操作之间的区别,并自己推断结论,因为只有您拥有完整的代码.从一种方法更改为另一种方法可能会更改调用顺序. 顺便说一句,您可以通过使用类System.Diagnostics.EventLog msdn.microsoft/zh-cn/library/system.diagnostics.eventlog.aspx [ ^ ].如果使用调试器,则可以引入时间延迟,该时间延迟可以更改图片(竞赛条件,请参见 http: //en.wikipedia/wiki/种族条件 [^ ]). 从UI线程之外的任何线程调用Invoke或BeginInvoke所使用的委托都不会在调用线程上被调用.而是通过将其添加到UI线程的事件队列中来调度的. UI检索进行调用所需的委托和参数,并在UI线程上调用它.如果使用BeginInvoke,则该方法将在委托和调用参数排队后立即返回,但是Invoke阻止调用,直到在UI线程上实际调用了委托为止.这种不同的行为可能导致某些操作的顺序不同. 您可以分析代码和/或使用EventLog找出会发生什么. 另请参阅我过去的解决方案: Control.Invoke()与Control.BeginInvoke() [ ^ ], Treeview Scanner和MD5的问题 [ ^ ].
更多推荐
WPF BeginInvoke和EntityFramework
发布评论