[Wp8.1ui Control Programming] Windows Phone Big Data network picture List for asynchronous loading and memory optimization

Source: Internet
Author: User

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.

Data.cs file Main code--------------------------------------------------------------------------------------------------------------- ---//The data class derives from INotifyPropertyChanged and is used to implement the event of a binding property change that can be updated to the UI after an asynchronous request is completed     Public classdata:inotifypropertychanged {//Picture Name Properties         Public stringName {Get;Set; } //the current Page object that is used to trigger the UI thread         PublicPage Page {Get;Set; } //the network address of the picture        PrivateUri Imageuri;  PublicUri Imageuri {Get            {                returnImageuri; }            Set            {                if(Imageuri = =value) {                    return; } Imageuri=value; BitmapImage=NULL; }        }        //if the object is referenced, it is used to store the downloaded picture objectWeakReference bitmapImage; //The ImageSource property is used on the image control that is bound to the list         PublicImageSource 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; ElseDebug.WriteLine ("data has been recycled"); }                //The weak references have been recycled. Then asynchronous download via the Image network address                if(Imageuri! =NULL) {Task.Factory.StartNew ()={downloadimage (Imageuri);}); }                return NULL; }        }        //How to download pictures        voidDownloadimage (ObjectState ) {HttpWebRequest Request= Webrequest.createhttp (state asUri); Request.        BeginGetResponse (downloadimagecomplete, request); }        //callback method to complete image download        Async voiddownloadimagecomplete (IAsyncResult result) {HttpWebRequest request= result. AsyncState asHttpWebRequest; HttpWebResponse Response=(HttpWebResponse) request.            EndGetResponse (result); //reading data from the networkStream stream =Response.            GetResponseStream (); intLength =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 that the network downloads to, the object that belongs to the background thread, cannot be used on the UIStream Streamforui =NewMemoryStream (length); byte[] buffer =New byte[length]; intRead=0;  Do{Read= Stream. Read (Buffer,0, length); Streamforui.write (Buffer,0, read); }  while(Read = =length); Streamforui.seek (0, Seekorigin.begin); //triggering the UI thread to process bitmaps and UI updates            awaitPage.Dispatcher.RunAsync (Coredispatcherpriority.normal, () ={BitmapImage BM=NewBitmapImage (); Bm.                    SetSource (Streamforui.asrandomaccessstream ()); //storing the Bitmap object in a Reference object                    if(BitmapImage = =NULL) BitmapImage=NewWeakReference (BM); ElseBitmapimage.target=BM; //triggering changes to UI binding propertiesOnPropertyChanged ("ImageSource");        }            ); }        //Property Change Event       Async voidOnPropertyChanged (stringProperty ) {            varhander =propertychanged; if(Hander! =NULL)                awaitPage.Dispatcher.RunAsync (Coredispatcherpriority.normal, () ={hander ( This,NewPropertyChangedEventArgs (property));        }); }         Public EventPropertyChangedEventHandler propertychanged; }

(2 ) using the ListView control is bound to data the data collection for the object.

MainPage.xaml file Main code-------------------------------------------------------------------------------------------------- ----------------    <ListViewx:name= "ListView">        <listview.itemtemplate>            <DataTemplate>                <StackPanel>                    <TextBlockText="{Binding Name}"Height= "a"></TextBlock>                    <ImageSource="{Binding ImageSource}"Width= "$"Height= "$"></Image>                </StackPanel>            </DataTemplate>        </listview.itemtemplate>    </ListView>
MainPage.xaml.cs file Main code--------------------------------------------------------------------------------------------------------------- --- PublicMainPage () {InitializeComponent (); //Create a collection of data with 1000 objectsList<data> Items =NewList<data>();  for(inti =0; I < +; 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 listItems.Add (NewData {Name ="Test"+ I, Page = This, Imageuri =NewUri ("http://pic002.cnblogs.com/images/2012/152755/2012120917494440.png?index="+i)}); } Listview.itemssource=Items; }

Source code Download: Http://vdisk.weibo.com/s/zt_pyrfNHoezI

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.