Page load is very card
One of my applications has a page to manage the raw material library, as shown in Figure 1, which is a pivot page with each pivot item listing a class of raw materials. The entire pivot page is tied to a Manageingredientsviewmodel object, each pivot item is bound to a Ingredientgroupviewmodel object, which The Ingredientgroupviewmodel object is created at run time based on data from the raw material library.
Figure 1
The current practice is to load the data through LINQ to SQL in the Manageingredientsviewmodel constructor, and then create the corresponding Ingredientgroupviewmodel object, as shown in code 1. This kind of synchronous loading data is very common and intuitive, but if there is more data and is accompanied by disk or network access, it may cause the page to load very card.
Code 1
I want to load the data asynchronously and load its data only when the user is viewing a pivot item, which ensures that the page remains responsive while avoiding loading redundant data. In this article, we will explore how to implement these effects through the Task Parallel library (tasks Parallel library,tpl) In the context of this application.
Start a task
First, I don't want to load all the data from the start, so replace the previous Code 1 with the following code 2, which is responsible for creating a set of empty Ingredientgroupviewmodel objects. Because the ItemsSource property of the pivot control and the Ingredientgroups property bindings of the Manageingredientsviewmodel object, the pivot control automatically creates an empty set of pivot items.
Code 2