I have a performance problem with my application, when I load a TabItem (each TabItem is bound to a ViewModel, each ViewModel having a DataTemplate). To solve this problem, I use an asynchron开发者_C百科ous loading in ViewModel constructor :
public MyViewModel(MyObject entity)
{
// WpfContext it's my Dispatcher
Task.Factory.StartNew(() => WpfContext.Invoke(() =>
{
//Initialisation
LoadMyObject(entity);
}));
}
With this solution, the first time the TabItem is loaded, it takes some times and seems not really asynchronous. For the other loads, it works good and asynchronously. I don't know exactly why. Any suggestion ?
Invoke
on a Dispatcher is a blocking call for both the background thread of your Task and then also the UI thread (once it decides to actually run your code).
It seems asynchronous sometimes because the UI thread is busy showing the new Tab, and so the Invoke
from the background thread is blocking until the UI thread has time to process it. When it seems like it is synchronous, the Invoke call is being processed by the UI thread before the new Tab is being displayed. So, in the end, I think you have a race condition.
To resolve this, you may need to refactor your LoadMyObject
method so it can be run on the background thread, or you could use the Dispatcher.BeginInvoke method and provide it a lower priority to ensure the display of your new Tab precedes the processing of the LoadMyObject
call
精彩评论