11.2.4 asynchronous loading and memory optimization for large data network picture lists
Virtualization technology allows a large list of data on a Windows phone to not worry about loading all of the data at once, ensuring the process of the UI. For virtualization technology, we're not just relying on it to load data into the list, but we can also take advantage of the virtualization features to do more things. One important feature of virtualization technology is that it can accurately determine which list items are on the phone screen and dynamically update the data. Based on this feature, we can make more optimizations to the function of the list.
So here's an example of how to use virtualization to make a list of performance optimizations. There is a need to implement a picture of the list, the pictures are from the network, and then the data collection is also very large. This network picture list function will face two problems, one is that the loading of the picture will be time-consuming, and the other is that when the continuous sliding will let the data collection load of the memory will be more and more high.
For the first problem, it can be solved asynchronously, so that when the list is loaded, the picture is displayed again, and the list is loaded very quickly for the first time. Then we can call the network request through the background thread to download the picture, download the picture and then trigger the UI thread to display the picture.
The second problem is to solve the memory problem, so you can use the weak reference type (WeakReference Class) to store the image's data. A weak reference is an object that is not guaranteed not to be reclaimed by the garbage collector, it has a relatively short life cycle, and when the garbage collector scans the area of memory it governs, it reclaims its memory once it finds an object with only a weak reference, but in general, the garbage collector's thread priority is low. You will not soon find those objects that have only weak references. When the use of memory affects the smooth running of the program, the garbage collector, in order to prioritize the existence of long-time weak reference objects to reclaim, thereby freeing up memory. So a weak reference is particularly appropriate in this case, where a large amount of memory is used, but it is easy to re-create a picture object after garbage collection. After the picture is downloaded, it will be stored in the weak reference object, when the data is collected, and then asynchronous loading, of course, you can also save the picture with a separate storage, which also eliminates the request for network operation again.
Let's take an example of asynchronous loading and memory optimization for a network picture list:
Code Listing 11-8 : Network Picture List (source code: Chapter 11th \examples_11_8)
(1) The data class is created, which encapsulates the logic of loading images and weak references asynchronously.
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
Data.cs File Main code------------------------------------------------------------------------------------------------------------ ------The // data class is derived from INotifyPropertyChanged, to implement a binding property change event that can be updated to the UI after an asynchronous request is completed public class Data: INotifyPropertyChanged { // Picture Name Attribute public string name { get; set; } // Current Page object that triggers the UI thread public Page Page { Web address of get; set; } // pictures private uri imageuri; public Uri ImageUri { get { return imageUri; } set { if (Imageuri == value) { return; } imageuri = value; bitmapimage = null; } } // if the object is referenced, For storing downloaded picture objects WeakReference bitmapImage; The // imagesource property is used to bind to the list of image controls public ImageSource ImageSource { get { if (bitmapimage != null) { // If the weak reference is not reclaimed, the value of the weak reference is taken if (bitmapimage.isalive) return (ImageSource) bitmapimage.target; else debug.writeline ("Data has been recycled"); } // weak references have been recycledThen asynchronous download through the image network address if (imageuri != null) { task.factory.startnew (() =>{ downloadimage (ImageUri);}); } return null; } } // How to download images void downloadimage (object state) { &Nbsp; httpwebrequest request = webrequest.createhttp (state as uri); request. BeginGetResponse (downloadimagecomplete, request); } // complete the callback method for image download Async void downloadimagecomplete (Iasyncresult result) { httpwebrequest request = result. asyncstate as httpwebrequest; HttpWebResponse response = (HttpWebResponse) request. EndGetResponse (Result); // reading data from the network &nbSp; stream stream = response. GetResponseStream (); int length = int. Parse (response. headers["Content-length"]); // Note that you need to re-copy the data stream, or cross-threading errors will occur // The picture data stream downloaded to the network, the object belonging to the background thread, cannot be used on the UI stream streamforui = new memorystream (length); byte[] buffer = new byte[length]; int read=0; do { read = stream. Read (buffer, 0, length); streamforui.write (Buffer, 0, read); } while (read == length); streamforui.seek (0, seekorigin.begin); // triggers the UI thread to process bitmaps and UI updates await page.dispatcher.runasync (CoreDispatcherPriority.Normal, () => { bitmapimage bm = new bitmapimage ();  BM. SetSource (Streamforui.asrandomaccessstream ()); // storing a Bitmap object in a Reference object if ( Bitmapimage == null) bitmapImage = new WeakReference (BM); else bitmapImage.Target = bm; //triggering changes to UI binding properties OnPropertyChanged ("ImageSource"); } ); } // Property Change Events async void onpropertychanged (String property) { var hander = PropertyChanged; if (hander != null) awAit page.dispatcher.runasync (coredispatcherpriority.normal, () => { hander (this, new propertychangedeventargs (property)); }); } public event PropertyChangedEventHandler PropertyChanged; }
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
(2 ) using the ListView control is bound to data the data collection for the object.
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
MainPage.xaml File Main code------------------------------------------------------------------------------------------------------ ------------ <listview x:name= "ListView" > <ListView.ItemTemplate> <DataTemplate> <StackPanel> <textblock text= "{binding name}" Height= "80" ></TextBlock> <image source= "{Binding imagesource}" Width= " " height= "></Image> " &nbsP;</stackpanel> </datatemplate > </ListView.ItemTemplate> < /listview>
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
MainPage.xaml.cs File Main code--------------------------------------------------------------------------------------------------- --------------- public mainpage () { initializecomponent (); // Create a collection of data with 1000 objects List<Data> Items = New list<data> (); for (int i = 0 ; i < 1000; i++) { // add index=i after the network address to ensure that each network address is different // this will not generate a network data cache, closer to the real network picture list items.add (new data { name = "Test" +&nbsP;i, page = this, imageuri = new uri ("http://pic002.cnblogs.com/images/2012 /152755/2012120917494440.png?index= " + i) }); } listview.itemssource=items; }
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
650) this.width=650; "src=" Http://images.cnitblog.com/i/152755/201406/021430521454984.png "/>
This article comes from the deep understanding of Windows Phone 8.1 UI Control programming
Source code Download: Http://vdisk.weibo.com/s/zt_pyrfNHoezI
Welcome to follow my Weibo @wp forestry administration
WP8.1 Technology Group: 372552293
[Wp8.1ui Control Programming] Windows Phone Big Data network picture List for asynchronous loading and memory optimization