[英]Windows Phone 8.1 WinRT memory leak with ObservableCollection
我正在處理在MapControl
上顯示的大量對象(POI)。 我正在幫助自己使用MVVM Light來遵守MVVM方法的規則。
由於我有義務在地圖上顯示的每個對象,我都用MapItemsControl
集合,而不是MapElements
之一。 此集合結合到所述ObservableCollection<PushpinViewModel>
對象( Pushpins
在對應) ViewModel
。 當我想要刷新Pushpins
時,一切都按預期工作。 問題是內存泄漏。 但首先,一些代碼可視化問題:
XAML:
<maps:MapControl x:Name="Map"
x:Uid="MapControl">
<maps:MapItemsControl ItemsSource="{Binding Pushpins}">
<maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Image}"/>
</DataTemplate>
</maps:MapItemsControl.ItemTemplate>
</maps:MapItemsControl>
MainViewModel:
public class MainViewModel : ViewModelBase
{
public RelayCommand AddCommand { get; set; }
public RelayCommand ClearCommand { get; set; }
public RelayCommand CollectCommand { get; set; }
public ObservableCollection<PushpinViewModel> Pushpins { get; set; }
/* Ctor, initialization of Pushpins and stuff like that */
private void Collect()
{
GC.Collect(2);
GC.WaitForPendingFinalizers();
GC.Collect(2);
PrintCurrentMemory();
}
private void Clear()
{
Pushpins.Clear();
PrintCurrentMemory();
}
private void Add()
{
for (int i = 0; i < 1000; i++)
{
Pushpins.Add(new PushpinViewModel());
}
PrintCurrentMemory();
}
private void PrintCurrentMemory()
{
Logger.Log(String.Format("Total Memory: {0}", GC.GetTotalMemory(true) / 1024.0));
}
}
PushpinViewModel:
public class PushpinViewModel: ViewModelBase
{
public string Image { get { return "/Assets/SomeImage.png"; } }
~PushpinViewModel()
{
Logger.Log("This finalizer never gets called!");
}
}
現在,請考慮以下方案。 我添加到Pushpins
集合千PushpinViewModel
元素。 它們被渲染,內存被分配,一切都很好。 現在我想清除集合,並添加另一個(在真實場景中不同)1000個元素。 所以,我調用了Clear()
方法。 但是......沒有任何反應! Pushpins
被清除,但PushpinViewModel
的終結不叫! 然后我再次添加1000個元素,我的內存使用量翻倍。 你可以猜到接下來會發生什么。 當我重復這個Clear()
- Add()
程序3-5次我的應用程序崩潰。
那么,問題是什么? 顯然, ObservableCollection
在對其執行Clear()
之后保持對PushpinViewModel
對象的引用,因此它們不能被垃圾回收。 當然,強制GC執行垃圾收集並沒有幫助(有時甚至會使情況變得更糟)。
現在困擾我2天了,我嘗試了許多不同的場景來嘗試克服這個問題,但說實話,沒有任何幫助。 只有一件事物VehiceViewModel
- 我不記得確切的情況,但是當我指定了Pushpins = null
,然后做了更多的事情時, VehiceViewModel
被摧毀了。 但這對我不起作用,因為我還記得在Clear()
之后我在地圖上可視化這些引腳時遇到了問題。
你有什么想法會導致這種內存泄漏嗎? 我如何強迫OC
的成員摧毀? 也許OC
有某種替代方案? 在此先感謝您的幫助!
編輯:
我使用XAML Map Control進行了一些測試 - https://xamlmapcontrol.codeplex.com/ ,結果令人驚訝。 添加> 1000個元素的整體地圖性能比原生MapControl
,但是,如果我調用Add()
x1000,然后調用Clear()
,然后Add()
PushpinViewModel
,則PushpinViewModel
的終結器調用! 內存被釋放,應用程序不會崩潰。 所以微軟的MapControl
肯定有問題......
好的,這是我模仿MapItemsControl
所做的行為。 請注意,這是非常未經測試的 - 它適用於我的應用程序,但實際上並沒有在其他任何地方嘗試過。 我從未測試過RemoveItems
函數,因為我的應用程序只是將項添加到ObservableCollection
並清除它們; 它永遠不會逐步刪除項目。
另請注意,它使用綁定的項的哈希碼標記XAML圖釘; 這是它如何識別集合更改時從地圖中刪除哪些圖釘。 這可能不適用於您的情況,但似乎是有效的。
用法:
注意: NumberedCircle
是一個用戶控件,它只是一個紅色圓圈,在其中顯示一個數字; 替換為您想要用作圖釘的任何XAML控件。 Destinations
是我的ObservableCollection
對象,它具有Number
屬性(顯示在圖釘內)和Point
屬性(圖釘位置)。
<map:MapControl>
<i:Interaction.Behaviors>
<behaviors:PushpinCollectionBehavior ItemsSource="{Binding Path=Destinations}">
<behaviors:PushpinCollectionBehavior.ItemTemplate>
<DataTemplate>
<controls:NumberedCircle Number="{Binding Path=Number}" map:MapControl.Location="{Binding Path=Point}" />
</DataTemplate>
</behaviors:PushpinCollectionBehavior.ItemTemplate>
</behaviors:PushpinCollectionBehavior>
</i:Interaction.Behaviors>
</map:MapControl>
碼:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xaml.Interactivity;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls.Maps;
namespace Foo.Behaviors
{
/// <summary>
/// Behavior to draw pushpins on a map. This effectively replaces MapItemsControl, which is flaky as hell.
/// </summary>
public class PushpinCollectionBehavior : DependencyObject, IBehavior
{
#region IBehavior
public DependencyObject AssociatedObject { get; private set; }
public void Attach(Windows.UI.Xaml.DependencyObject associatedObject)
{
var mapControl = associatedObject as MapControl;
if (mapControl == null)
throw new ArgumentException("PushpinCollectionBehavior can be attached only to MapControl");
AssociatedObject = associatedObject;
mapControl.Unloaded += MapControlUnloaded;
}
public void Detach()
{
var mapControl = AssociatedObject as MapControl;
if (mapControl != null)
mapControl.Unloaded -= MapControlUnloaded;
}
#endregion
#region Dependency Properties
/// <summary>
/// The dependency property of the item that contains the pushpin locations.
/// </summary>
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(object), typeof(PushpinCollectionBehavior), new PropertyMetadata(null, OnItemsSourcePropertyChanged));
/// <summary>
/// The item that contains the pushpin locations.
/// </summary>
public object ItemsSource
{
get { return GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
/// <summary>
/// Adds, moves, or removes the pushpin when the item source changes.
/// </summary>
private static void OnItemsSourcePropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var behavior = dependencyObject as PushpinCollectionBehavior;
var mapControl = behavior.AssociatedObject as MapControl;
// add the items
if (behavior.ItemsSource is IList)
behavior.AddItems(behavior.ItemsSource as IList);
else
throw new Exception("PushpinCollectionBehavior needs an IList as the items source.");
// subscribe to changes in the collection
if (behavior.ItemsSource is INotifyCollectionChanged)
{
var items = behavior.ItemsSource as INotifyCollectionChanged;
items.CollectionChanged += behavior.CollectionChanged;
}
}
// <summary>
/// The dependency property of the pushpin template.
/// </summary>
public static readonly DependencyProperty ItemTemplateProperty =
DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(PushpinCollectionBehavior), new PropertyMetadata(null));
/// <summary>
/// The pushpin template.
/// </summary>
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
#endregion
#region Events
/// <summary>
/// Adds or removes the items on the map.
/// </summary>
private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
AddItems(e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
RemoveItems(e.OldItems);
break;
case NotifyCollectionChangedAction.Reset:
ClearItems();
break;
}
}
/// <summary>
/// Removes the CollectionChanged event handler from the ItemsSource when the map is unloaded.
/// </summary>
void MapControlUnloaded(object sender, RoutedEventArgs e)
{
var items = ItemsSource as INotifyCollectionChanged;
if (items != null)
items.CollectionChanged -= CollectionChanged;
}
#endregion
#region Private Functions
/// <summary>
/// Adds items to the map.
/// </summary>
private void AddItems(IList items)
{
var mapControl = AssociatedObject as MapControl;
foreach (var item in items)
{
var templateInstance = ItemTemplate.LoadContent() as FrameworkElement;
var hashCode = item.GetHashCode();
templateInstance.Tag = hashCode;
templateInstance.DataContext = item;
mapControl.Children.Add(templateInstance);
Tags.Add(hashCode);
}
}
/// <summary>
/// Removes items from the map.
/// </summary>
private void RemoveItems(IList items)
{
var mapControl = AssociatedObject as MapControl;
foreach (var item in items)
{
var hashCode = item.GetHashCode();
foreach (var child in mapControl.Children.Where(c => c is FrameworkElement))
{
var frameworkElement = child as FrameworkElement;
if (hashCode.Equals(frameworkElement.Tag))
{
mapControl.Children.Remove(frameworkElement);
continue;
}
}
Tags.Remove(hashCode);
}
}
/// <summary>
/// Clears items from the map.
/// </summary>
private void ClearItems()
{
var mapControl = AssociatedObject as MapControl;
foreach (var tag in Tags)
{
foreach (var child in mapControl.Children.Where(c => c is FrameworkElement))
{
var frameworkElement = child as FrameworkElement;
if (tag.Equals(frameworkElement.Tag))
{
mapControl.Children.Remove(frameworkElement);
continue;
}
}
}
Tags.Clear();
}
#endregion
#region Private Properties
/// <summary>
/// The object tags of the items this behavior has placed on the map.
/// </summary>
private List<int> Tags
{
get
{
if (_tags == null)
_tags = new List<int>();
return _tags;
}
}
private List<int> _tags;
#endregion
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.