Windows phone application development [21]- picture performance optimization

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

In the windows phone often in the list will always contain rich text and pictures mixed data information. For a list of data in addition to talk about the virtual ListBox control their own data. Although the WP hardware with the release of SDK 8 applications can use memory space has been greatly expanded. But in order to ensure the WP platform experience in low the configuration model the same application user. Performance tuning is unable to avoid problems.

Early is subject to the CE kernel to the hardware limits in Windows phone version 7. The single application of the highest memory peak value is 90M. when the application memory exceeds the peak without any prompting will automatically exit. With Windows Phone 8 using NT kernel. The hardware was extended. In WP SDK 8 on the memory limit with the continuous evolution of equipment and the existence of different peak. The higher the memory limit because of the type of equipment and different. Usually, has more than 1 GB memory of the mobile phone is considered high memory device, but it also depends on equipment and. For example, if the mobile phone has a high resolution camera, application purposes, the mobile phone will be regarded as low memory devices. The following table lists these category in the default memory limit and higher memory limit:

2013-11-06_173202

Of course, we can also through the acquisition of DeviceExtendedProperties.GetValue (String) method to check for ApplicationWorkingSetLimit values, to check the application memory peak available.

Exit automatically and relative Windows phone version 7 and reached the peak after practice. WP SDK 8 to do more options. Instead of simply using directly out of the way. In order to ensure that our application can cover more WP terminal. For the low-end configuration of the mobile phone. You can request more memory or completely abandon the low-end adaptation. Application of hope are available to all mobile phone (but it may use more memory and other mobile phone task), the FunctionalCapability must be added to the application manifest file. To exit the low memory devices, the Requirements must be added to the list of entries.

2013-11-06_180318

With this option. It can be free to choose the current application in memory using the adapted models. Of course for the best method. And from the perspective of the application and optimize our application. To low-end models can fit effect.

This article to optimize a picture windows phone application performance of the key.

The first set XAML file windows phone common picture format PNG and jpg. support JPG relative to the PNG decoding speed faster. A single picture display is not obvious. In the mass data UI present to a certain expression. So in principle for resource selection in JPG format picture to give priority to. But if UI is similar to Backgound Image background pictures have clear requirements. You can only choose the format of PNG.Jpg does not support transparent background.

The picture to the XAML file. The decoding process pictures all by default are synchronized in the UI thread, so if in the following manner display pictures will block the UI thread to a certain extent:

1: <Image Source=”{Binding ImageUrl}”/>

Xaml in the UI display of bingding image decoding. The decoding is completed will display UI up. And this process UI process blocks until the decoding end will be shown. So usually we picture resources for Image obtained by the background process to load:

1: <Image> 2: <Image.Source> 3: <BitmapImage UriSource="{Binding ImgUrl}" CreateOptions="BackgroundCreation"/> 4: </Image.Source> 5: </Image>

But even so we set the actual test and found no obvious do not. But if we add a big picture. Obviously he delay time and UI block is loaded. In fact, here we UI control picture display will be divided into two forms a binding another direct assignment through the back way. When we are in the code to a Image control direct assignment BitmapImage. for the big picture usually encounter overflow memory OutOfMemory problem. The following code to load a big picture will appear:

1: using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication()) 2: { 3: const string filePath = @"Shared\ShellContent\FlipBackImage.jpg"; 4: var filename = "Image.png"; 5: var stream = !isoFile.FileExists(filename) ? null : isoFile.OpenFile(filename, FileMode.Open, FileAccess.Read); 6: if (stream != null) 7: { 8: if (isoFile.FileExists(filePath)) 9: isoFile.DeleteFile(filePath); 10: 11: Debug.WriteLine("currentMemory"+DeviceStatus.ApplicationCurrentMemoryUsage); 12: var bi = new BitmapImage(); 13: bi.CreateOptions = BitmapCreateOptions.None; 14: bi.SetSource(stream); //out of memory exception getting here 15: 16: var wbm=new WriteableBitmap(bi); 17: using (var streamFront = isoFile.OpenFile(filePath, FileMode.Create)) 18: { 19: wbm.SaveJpeg(streamFront, 691, 336, 0, 80); 20: } 21: Deployment.Current.Dispatcher.BeginInvoke(() => Utils.DisposeImage(wbm)); 22: } 23: }

In fact, the overflow occurs outofMemory memory problems if a careful analysis will find. Added to this code test using high resolution pictures 1500*1000 width and height. Each pixel pixel memory space for 4KB. we calculate a big picture in UI rendering display memory space: 1500 x 1100 x 4 = 6600000 bytes = > 6.5 MB approached 6.5M about the size of mobile phone. Due to the limited screen resolution. The bigger picture should be displayed in low resolution sampling. If the image is larger than the 2000*2000 of the display will be slowed down. Especially in the low-end equipment is more obvious. There are people on display solutions given the big picture of Windows Phone:

A part of a display image each time only. The first picture is loaded into a T:System.Windows.Media.Imaging.WriteableBitmap, and then use the LoadJpeg (WriteableBitmap, Stream) expansion method to load images

This can effectively avoid the above appearoutofmemoryAbnormal memory leak.In fact, the relativeWriteableBitmapThe object has a better way.When we load the picture resources.In fact, a large part of memory consumption in the picture decoding..If we can useWriteableBitmapTheDecodePixelWidth AndDecodePixelHeight Property to avoid the picture re decoding.Access to data streamStreamIn theMemoryThe operation object in memory.This will avoid the memory in the show too much overhead.But here it means attention isDecodePixelWidth AndDecodePixelHeightIn some cases may be a null value isNull.The need for additional treatment..

Also if you used the panoramic view control. The default background is black. Most of the cases we will set the background image to fill. In fact, background is a special element, is limited to 2048X2048. Over this size will be cut, this means using a length width more than 2048 pixels of the picture, the picture is not fully display. In order to avoid the occurrence of such a situation, the WP7 platform will automatically reduce the pixel image to 2048X2048. This point is different from the Silverlight desktop application, should be Silverlight no such restrictions.

Here to mention that.WriteableBitmap was present only in the Windows Phone SDK provides a SaveJpeg method. The source code into an JPEG stream. But do not provide a method for PNG format. If you need through the WriteableBitmap code output into a PNG format of stream stream. You can refer to the following solutions:

You can use writeablebitmapex open source third party add WritePNG an extended method for WriteableBitmap expansion method is used to realize the conversion of PNG format of stream stream

WriteableBitmapEX Project Document

In fact, nature is based on the WriteableBitmap object to add two expansion method. The method is based on the realization of ToolStackCRCLib and ToolStackPNGWriterLib library. And transplantation of the Windows version of phone, the core extensions are as follows:

1: using System.IO; 2: using System.IO.IsolatedStorage; 3: using System.Windows.Shapes; 4: using System.Windows.Media; 5: using ToolStackCRCLib; 6: using ToolStackPNGWriterLib; 7: 8: namespace System.Windows.Media.Imaging 9: { 10: /// <summary> 11: /// WriteableBitmap Extensions for PNG Writing 12: /// </summary> 13: public static partial class WriteableBitmapExtensions 14: { 15: /// <summary> 16: /// Write and PNG file out to a file stream. Currently compression is not supported. 17: /// </summary> 18: /// <param name="image">The WriteableBitmap to work on.</param> 19: /// <param name="stream">The destination file stream.</param> 20: public static void WritePNG(this WriteableBitmap image, System.IO.Stream stream) 21: { 22: WritePNG(image, stream, -1); 23: } 24: 25: /// <summary> 26: /// Write and PNG file out to a file stream. Currently compression is not supported. 27: /// </summary> 28: /// <param name="image">The WriteableBitmap to work on.</param> 29: /// <param name="stream">The destination file stream.</param> 30: /// <param name="compression">Level of compression to use (-1=auto, 0=none, 1-100 is percentage).</param> 31: public static void WritePNG(this WriteableBitmap image, System.IO.Stream stream, int compression) 32: { 33: PNGWriter.DetectWBByteOrder(); 34: PNGWriter.WritePNG(image, stream, compression); 35: } 36: } 37: }

Only need to call the WriteableBitmap method of WritePng can easily achieve the output file format a PNG stream stream object. About the library specific use please refer to the official documents. The image of the API is based on resolution decoding [picture itself except Downsampling reduced pixel sampling. If you download a number of 600X600 images, But only in 60X60 so small display, So also with the original resolution decoding will waste your application's memory. Fortunately Windows Phone Platform to provide a PictureDecoder interface, The ability to customize the resolution to the decoded picture to save more memory overhead:

1: image.Source = PictureDecoder.DecodeJpeg(jpgStream, 60, 60);

Just mentioned above, UI XAML file we process images in two ways:

In two ways:

A: through the backstage code on the Image Xaml file control direct assignment

B: The present Image. data binding

In fact, if the use of background assignment way. First need a Image control is defined in the Xaml document. Using UriSource or Source assignment operator. In fact, if you carefully study this problem will be found. Even empty the Source property is null and the Image from the visual tree removed, Image memory is not released, check the memory footprint and none the less. The page and exit did not immediately picture occupied content for garbage collection. The essence of the problem of the image cache still occupy memory resources. This is actually a reserved performance optimization mechanism, In fact, in order to avoid over and over loading and decoding the same picture. Windows Phone in memory to open a buffer, using pictures and reuse of resources it is convenient and quick, slow down every time the UI response time. Although the image cache it is very helpful to improve the performance, but sometimes unnecessary memory consumption. In particular we intend to recover those not shown in the picture and the memory timely release. In fact, he can use the following code to operate the image space XAML can do:

1: BitmapImage bitmapImage = image.Source as BitmapImage; 2: bitmapImage.UriSource = null; 3: image.Source = null;

On top ofxamlWe noted that the file codeBitmapImage ObjectCreateOptionsSet toBackgroundCreation. To reduce theUiThread is blocked in the display.In factBitmapImageObjectCreateOptionsThe default value isDelayCreation. When you set in the page.After the success of a loading page.Of course, try to access the image size,But found that the null values.Null.You might ask: 为什么当已经完成图片创建时仍不会返回图片的大小?This is becauseCreateOptions Property is set to the default“DelayCreation”, That is to say when the Source property of the BitmapImage is set to a Image or ImageBrush on the visual tree, The only objects in real need only when it is created. When this really is created when Image XAML file controls will automatically trigger the ImageOpened event. Can obtain the actual size picture here.

Go back to the CreateOptions property of the BitmapImage object. In fact, when the page loads. Can a lot of BitmapImage, but does not consume any resources (CPU and memory) until the program requires a specific picture will truly create them. Of course, if you want to create the image on the page is displayed. Also is the immediate implementation of the create operation. CreateOptions can be set to “ None”. About the nature of fair use and there will be mentioned.

The above mentioned a lot on the picture may be in the actual operation performance and reduce memory overhead some small details. In fact, the real project application scenarios. We mostly use the collection of Listbox data binding controls to display for a batch of images. Many people are using MVVM model to show how to bind data. In MVVM mode optimized control picture performance? Second half focus on this problem.

First, create a new project. Named: PictureMemoryUsageDemo. in the page Xaml file using Listbox to use MVVM form to bind the picture display, Xaml UI layout is as follows:

1: <!--ContentPanel - place additional content here--> 2: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="24,0,12,0"> 3: <ListBox x:Name="ControlMemory_LB" ItemsSource="{Binding TripPictureCol}" SelectionChanged="ControlMemory_LB_SelectionChanged"> 4: <ListBox.ItemsPanel> 5: <ItemsPanelTemplate> 6: <tool:WrapPanel Orientation="Horizontal"></tool:WrapPanel> 7: </ItemsPanelTemplate> 8: </ListBox.ItemsPanel> 9: <ListBox.ItemTemplate> 10: <DataTemplate> 11: <StackPanel Margin="10,0,0,0"> 12: <Image Source="{Binding TripPictureUrl}" Width="100" Height="100"></Image> 13: </StackPanel> 14: </DataTemplate> 15: </ListBox.ItemTemplate> 16: </ListBox> 17: </Grid>

A listBox is a single is simple binding a Image horizontal layout. The following code to bind a standard ViewModel binding form:

1: void MainPage_Loaded(object sender, RoutedEventArgs e) 2: { 3: if (_tripPicViewModel == null) 4: _tripPicViewModel = new TripPictureViewModel(); 5: this.DataContext = _tripPicViewModel; 6: }

Z ViewModel simulation of a picture data ObserverCollection<T>Binding of ViewModel code set:

1: public class TripPictureViewModel:INotifyPropertyChanged 2: { 3: #region Property 4: public event PropertyChangedEventHandler PropertyChanged; 5: private ObservableCollection<TripPictureInfo> _tripPictureCol = new ObservableCollection<TripPictureInfo>(); 6: public ObservableCollection<TripPictureInfo> TripPictureCol 7: { 8: get { return _tripPictureCol; } 9: set 10: { 11: _tripPictureCol = value; 12: BindProertyChangedEventHandler("TripPictureCol"); 13: } 14: } 15: #endregion 16: 17: public TripPictureViewModel() 18: { 19: LoadTripAddressPictureData(); 20: } 21: 22: #region Action 23: 24: public void BindProertyChangedEventHandler(string propertyName) 25: { 26: if (string.IsNullOrEmpty(propertyName)) 27: return; 28: 29: PropertyChangedEventHandler eventHandler = this.PropertyChanged; 30: if (eventHandler != null) 31: eventHandler(this, new PropertyChangedEventArgs(propertyName)); 32: } 33: 34: public void LoadTripAddressPictureData() 35: { 36: string pictureHealderStr = "/Images/670("; 37: string pictureFooterStr = ").jpg"; 38: for (int count = 0; count <20; count++) 39: _tripPictureCol.Add(new TripPictureInfo() { CityName="Ukraine", StatusCode=(count+1).ToString(), TripPictureUrl=pictureHealderStr+(count+1).ToString()+pictureFooterStr}); 40: } 41: #endregion 42: 43: }

A standard ViewModel binding to end like this. We directly open the page can be found that UI showed lateral arrangement effect as follows in the UI.:

wp_ss_20131107_0002

Normally we in the page to bind a ListBox collection to the simple picture display. We do not make any of the images processed at this time. In this function based on the current application were recorded in the use process memory usage. In a separate add a memory usage record display page named MemoryLogView.xaml. The current application memory usage to get through the DeviceStatus.ApplicationCurrentMemoryUsage property. Then we should add log where records?

Have a look first to the life cycle of the entire PhoneApplicationPage first entered the MainPage. The calling process. By constructing method MainPage (). After InitializeComponent (Loaded) loaded after () event. Now the construction methods and Load events begin and end position don't add the current content monitoring log:

1: public MainPage() 2: { 3: LogRecordHelper.AddLogRecord("MainPage Init Before:", DeviceStatus.ApplicationCurrentMemoryUsage.ToString()+" B"); 4: InitializeComponent(); 5: this.Loaded += MainPage_Loaded; 6: LogRecordHelper.AddLogRecord("MainPage Init After:", DeviceStatus.ApplicationCurrentMemoryUsage.ToString() + " B"); 7: }

The Loaded method to add memory usage log monitoring:

1: void MainPage_Loaded(object sender, RoutedEventArgs e) 2: { 3: LogRecordHelper.AddLogRecord("MainPage Load Before:", DeviceStatus.ApplicationCurrentMemoryUsage.ToString() + " B"); 4: if (_tripPicViewModel == null) 5: _tripPicViewModel = new TripPictureViewModel(); 6: this.DataContext = _tripPicViewModel; 7: LogRecordHelper.AddLogRecord("MainPage Load After:", DeviceStatus.ApplicationCurrentMemoryUsage.ToString() + " B"); 8: }

When we open the application. The log will automatically record the current memory usage. The first to enter the application memory usage is as follows:

wp_ss_20131107_0003

Visible when the first into the application. In the MainPage constructor does not consume more memory. It is only when data are successfully loaded Load Before and Load After change is too large. From the log interface backup to MainPage repeatedly repeatedly found that memory usage is as follows:

wp_ss_20131107_0005

We can find obvious. The same data. By the page after the current memory gradually increased. But the process did not increase UI data. This is why? To solve this problem we add MainPage destructor. And when the function is executed to obtain the current memory usage:

1: ~MainPage() 2: { 3: LogRecordHelper.AddLogRecord("MainPage Destructor Excuted:", DeviceStatus.ApplicationCurrentMemoryUsage.ToString() + " B"); 4: }

We then repeat just operation. View of the current page is implemented?.MainPage page is in the exit of normal release of the page data memory, after several tests found that the destructor performed successfully, and record the current memory usage:

wp_ss_20131104_0001

While destructors performed successfully. Not every time to leave the MainPage page that is executed first need to explain the significance of the destructor. The whole life cycle of PhoneApplicationPage. Function is just the destructor and the constructor instead. When the object from its scope (for example, like the called function finishes), the system automatically performs the destructor releases the resource. In fact the reality is that the code we cannot control when the destructor is called, because it is determined by the garbage collector. The garbage collector to check for the presence of the application object is no longer in use. If the garbage collector that an object conforms to the destructor, then calls the destructor (if any), recovery of the object's memory. When the program exits also calls the destructor.

To return to the operation. Although we MainPage pages to the successful implementation of the destructor. Here are a few questions? Executive destructor is not performed in the left MainPage page. Another problem is that although we successfully performed the destructor but we found the actual memory usage and no reduction. How in the data binding MVVM touch next page release the memory space occupied?

If we leave the MainPage discovered the destructor is not performed. Then we must adopt the strategy. Generally we use data binding in DataContent=ViewModel. Leave the page because the DataContent property in the ViewModel View between the reference relationship dependence. In the View leave not destroyed. We can be in the OnRemovedFromJournal () method to weed out the reference and forced to do GC processing.:

1: protected override void OnRemovedFromJournal(JournalEntryRemovedEventArgs e) 2: { 3: this.DataContext = null; 4: GC.Collect(); 5: GC.WaitForPendingFinalizers(); 6: base.OnRemovedFromJournal(e); 7: }

dIn theOnRemovedFromJournalMethod of liftViewAndViewModelDependence.SuchViewTo secure the release of.Here refers to aOnRemovedFromJournalMethod execution time.This method is in factviewBy the method call stack when the pop-up.Also in theOnNavigatedFromTo perform the operation method. Is it enough to do? In fact weUIThe picture on the cached data still occupy memory space.It is in the left page before we need to briefly removed image cache data.

In the above Xaml file we ListBox binding entities set Image Source for just a picture of Url address entity is defined as follows:

1: public class TripPictureInfo 2: { 3: public string CityName { get; set; } 4: public string StatusCode { get; set; } 5: public string TripPictureUrl { get; set; } 6: }

Now if we want to leave the page. Cache data need to transform this new entity adds an attribute TirpPictureSource:

1: public class TripPictureInfo 2: { 3: public string CityName { get; set; } 4: public string StatusCode { get; set; } 5: public string TripPictureUrl { get; set; } 6: 7: private BitmapImage _tirpPictureSource = new BitmapImage() { CreateOptions = BitmapCreateOptions.BackgroundCreation 8: | BitmapCreateOptions.IgnoreImageCache 9: | BitmapCreateOptions.DelayCreation }; 10: public BitmapImage TirpPictureSource 11: { 12: get 13: {
15: _tirpPictureSource.UriSource = new Uri(TripPictureUrl,UriKind.RelativeOrAbsolute); 16: return _tirpPictureSource; 17: } 18: } 19: }

The CreateOptions property and set the BitmapImage to BackgroundCreation, IgnoreImageCache, DelayCreation. Physical properties on the UI ListBox data last modify Image Source binding to TirpPictureSource.

1: <!--ContentPanel - place additional content here--> 2: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="24,0,12,0"> 3: <ListBox x:Name="ControlMemory_LB" ItemsSource="{Binding TripPictureCol}" SelectionChanged="ControlMemory_LB_SelectionChanged"> 4: <ListBox.ItemsPanel> 5: <ItemsPanelTemplate> 6: <tool:WrapPanel Orientation="Horizontal"></tool:WrapPanel> 7: </ItemsPanelTemplate> 8: </ListBox.ItemsPanel> 9: <ListBox.ItemTemplate> 10: <DataTemplate> 11: <StackPanel Margin="10,0,0,0"> 12: <Image Source="{Binding TirpPictureSource}" Width="100" Height="100"></Image> 13: </StackPanel> 14: </DataTemplate> 15: </ListBox.ItemTemplate> 16: </ListBox> 17: </Grid>

When the page is left in the OnNavigatedFrom method to clear all cache image in nature is a set BitmapImage UrlSource is empty:

1: private void ClearImageCache() 2: { 3: if (_tripPicViewModel.TripPictureCol.Count > 0) 4: { 5: foreach(TripPictureInfo queryInfo in _tripPicViewModel.TripPictureCol) 6: queryInfo.TirpPictureSource.UriSource=null; 7: } 8: }

When the page is only to return the last page will perform the operation. At the same time, ObserverCollection and ViewModel in empty<T>The collection data when the page is left to add the current memory usage records. See when the page is the page cache the image data from the memory is recovered by the code as follows:

1: protected override void OnNavigatedFrom(NavigationEventArgs e) 2: { 3: LogRecordHelper.AddLogRecord("Clear Before:", DeviceStatus.ApplicationCurrentMemoryUsage.ToString() + " B"); 4: if (e.NavigationMode == NavigationMode.Back) 5: { 6: ClearImageCache(); 7: _tripPicViewModel.TripPictureCol.Clear(); 8: } 9: LogRecordHelper.AddLogRecord("Clear After:", DeviceStatus.ApplicationCurrentMemoryUsage.ToString() + " B"); 10: }

So we in the same operation to determine whether the current page left empty by the image cache memory usage, memory log are as follows:

wp_ss_20131107_0006

We can seeClear Before AndClear AfterThe contrast between the current memory usage,Clear Before Memory is66637824 [B] Clear After Memory usage is 15417344 [B].To calculate when the page left clear image cache data for the actual size: [(Clear After-Clear Before)/1024/1024]=[(66637824-15417344)/1024/1024]=48.84765625 M. It is in the page left clear images take up the cache size48.8M.

You can really see the effect of each page left. Memory is the main problem in the cache memory is not released picture resources. We only need to empty the cache resources can be in the picture page exit ram. When doubt is found on page left the destructor is still not implemented. Usually.NET Framework the garbage collector allocates memory implicit management object and release. But when the packaging window, the application files and network connections to these unmanaged resources, should use the destructor frees the resources. When the object is consistent with the destructor, will run the Finalize method object the garbage collector. Although the object the garbage collector can track package unmanaged resources of survival, but it does not know how to clean up these resources. Unmanaged source are common: ApplicationContext, Brush, Component, ComponentDesigner, Container, Context, Cursor, FileStream, Font, Icon, Image, Matrix, Object, OdbcDataReader, OleDBDataReader, Pen, Regex, Socket, StreamWriter, Timer, Tooltip Etc..

If you use UI Brush similar to those of unmanaged resources. Causes each to enter the page UI will automatically redraw. Increased memory consumption. But now we are currently not these objects, why the destructor in the exit after a period of time is still not implemented? In fact, problems mainly because in Code behind code to add ListBox a ControlMemory_LB_SelectionChanged event used to view individual photos:

1: private void ControlMemory_LB_SelectionChanged(object sender, SelectionChangedEventArgs e) 2: { 3: if (e.AddedItems.Count > 0) 4: { 5: TripPictureInfo tripPicInfo = this.ControlMemory_LB.SelectedItem as TripPictureInfo; 6: if (tripPicInfo == null) 7: return; 8: 9: this.ControlMemory_LB.SelectedIndex = -1; 10: this.NavigationService.Navigate(new Uri("/SinglePictureView.xaml?Url="+tripPicInfo.TripPictureUrl,UriKind.RelativeOrAbsolute)); 11: } 12: }

The ListBox object as because the event has subscription reference relations. At the same time as ListBox Mainpage sub object. So Mainpage page on the left is not destroyed. So here is very worth mentioning is left in the page. If the page object subscriptions backstage event. The cancellation of the event subscription. In order to ensure the destruction of normal View can exit, add a method to cancel the ListBox event subscription:

1:     private void ClearRegisterUIElementEvent() 2: { 3: this.ControlMemory_LB.SelectionChanged -= ControlMemory_LB_SelectionChanged; 4: }

At the same time the call to the OnRemovedFromJournal method to clear the event subscription method:

1: protected override void OnRemovedFromJournal(JournalEntryRemovedEventArgs e) 2: { 3: ClearRegisterUIElementEvent(); 4: this.DataContext = null; 5: GC.Collect(); 6: GC.WaitForPendingFinalizers(); 7: base.OnRemovedFromJournal(e); 8: }

Then continue on repetitive operation. To have a look the implementation of memory usage and the destructor:

wp_ss_20131107_0008

You can see when first entering the page was successfully cleared the image cache. When re entering the MainPage will immediately implement the destructor. Thus once again to create a new MainPage object in memory at the time the original first create a MainPage object View will be immediately destroyed. It can promptly destroyed the original View. in the testing process. Page the destructor is called, But memory does not reduce the destructor is GC recovery View., Do not represent the internal application resources are released. So the image cache data to separate processing, of course, if your UI is complicated. Contain unmanaged resources. You need to manually release the memory resources in the destructor of occupancy.

If you use the IOC+MVVM development mode. You need to add the following code in the OnRemovedFromJournal function:

1: Messenger.Default.Unregister<bool>(this, MessageToken.MessageListChanged);

Messenger.Default.Unregister<bool>(this, MessageToken.MessageListChanged);This statement is very important, if the VM in the init registration observed in Messenger, the system default will not be associated with this VM view destroyed, so we can be here for his destruction. Of course, such Messenger destruction we can write directly in VM in order to maintain the unity of the life cycle. Although the MVVM model can rich text mode using DataBinding mode to improve our design efficiency. But it also increases our windows phone memory leak difficulty. At the same time to refer to the whole life cycle of PhoneApplicationPage to properly handle the ram.

Download the source code: [https://github.com/chenkai/ReduceMemoryUseageDemo]

Contact Me: [@chenkaihome]

Reference material:

Clear image cache from Grid background 

OutOfMemoryException occure on WriteableBitmap

BitmapImage.CreateOptions

How to pass BitmapImage reference to BackgroundWorker.DoWork

Windows Phone page Jump event calling sequence

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Elsa at December 06, 2013 - 7:08 AM