Правильная утилизация SciChartSurface - PullRequest
0 голосов
/ 15 мая 2018

В настоящее время я использую структуру, аналогичную 50 ЭЭГ, например .Частью моего дизайна является добавление и удаление 10-50 графиков функций на лету, поэтому важно, чтобы я эффективно управлял своей памятью.Когда я запускаю профилировщик памяти в VS2015, я обнаруживаю, что каждый раз, когда я пытаюсь построить график функции из коллекции, SciChart.Charting.Visuals.Axes.LabelProviders.NumericTickLabel все еще остается в памяти.Как правильно расположить NumericTickLabel или удалить scichartsurface?

XAML.CS

    <ResourceDictionary>
       <DataTemplate x:Key="FunctionItemTemplate">
       <Grid>
           <s:SciChartSurface Name=FunctionSurface
                              RenderableSeries="{Binding RenderableSeriesCollections}"/>

       </Grid>
    </ResourceDictionary>

    <ListView Name="FunctionPlots
          ItemTemplate="{StaticResource FunctionItemTemplate}"
          ItemsSource="{Binding FunctionsCollection}" />

MainWindowViewModel.cs

public class MainWindowViewModel : INotifyProperty
{
       private ObservableCollection<FunctionPlotViewModel> _functionsCollection;

       public MainWindowViewModel()
       {
           FunctionsCollection = new ObservableCollection<FunctionPlotViewModel>();
       }

       public ObservableCollection<FunctionPlotViewModel> FunctionsCollection
       {
             get { return _functionsCollection;}
             set 
             {
                   _functionsCollection = value;
                   OnPropertyChanged("FunctionsCollection");     
             }  
       }

       public void RemoveLastFunctionPlot()
       {
              int lastIndex = FunctionCollections.Count - 1;
              FunctionCollections.Remove(lastIndex);
              //Doesn't Collect
              GC.Collect();
              GC.WaitForPendingFinalizer();
              GC.Collect();
       }

       public event PropertyChangedEventHanlder PropertyChanged;
       protected void OnPropertyChanged(string name)
       {
                PropertyChangedEventHanlder handler = PropertyChanged;

                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(name));

                }
        }

}

FunctionPlotViewModel.cs

 public class FunctionPlotViewModel: INotifyProperty
    {
       private ObservableCollection<IRenderableSeries> _renderableSeriesCollections;

       public FunctionPlotViewModel()
       {
           RenderableSeriesCollection = new ObservableCollection<IRenderableSeries>();
       }

       public ObservableCollection<IRenderableSeries> RenderableSeriesCollections
       {
             get { return _renderableSeriesCollections;}
             set 
             {
                   _renderableSeriesCollections= value;
                   OnPropertyChanged("RenderableSeriesCollections");     
             }  
       }

       public  void SetUpCustomAxis(double TimeOfDayInitial, IAxis AxisToBindTo)
       {
             var defaultSurface = RenderableSeriesCollections.FirstOrDefault().DataSeries.ParentSurface();
              if(defaultSurface == null)
              {
                  return;
              }
              var newAxis = new NumericAxis();
              var customNumericLabel = new CustomNumericLabelProvider();
              defaultSurface.XAxis = newAxis;
              Binding visibleRangeBinding = new Binding("VisibleRange");
              visibleRangeBinding.Source = AxisToBindTo;
              visibleRangeBinding.Mode = BindingMode.TwoWay;
              ((NumericAxis)defaultSurface.XAxis).SetBinding(NumericAxis.VisibleRangeProperty, visibleRangeBinding);

       }

       public void CleanUp()
       {
           var defaultSurface = RenderableSeriesCollections.FirstOrDefault().DataSeries.ParentSurface();
              if(defaultSurface == null)
              {
                  return;
              }
           foreach(var renderSeries in RenderableSeriesCollections)
           {
                renderSeries.DataSeries.Clear();
           }
           RenderableSeriesCollections.Clear();
           var token  = defaultSurface.SuspendUpdates();
           token.Dispose();

           //More things to do??
       }

       public event PropertyChangedEventHanlder PropertyChanged;
       protected void OnPropertyChanged(string name)
       {
                PropertyChangedEventHanlder handler = PropertyChanged;

                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(name));

                }
        }

}

CustomNumericLabelProvider.cs

     public class CustomNumericLabelProvider : NumericProvider
     {
       public override void OnBeginAxisDraw()
       {
       }

       public override string FormatLabel(IComparable dataValue)
       {
            if (dataValue == null)
                return String.Emtpy;
            return ConvertToTimeOfDay(dataValue);

       }

       public string ConvertToTimeOfDay(IComparable value)
       {
             //commented out for brevity
             return value;
       }

       public override string FormatCursorLabel(IComparable dataValue)
       {
            //commented out for brevity
            return dataValue;
       }

    }

1 Ответ

0 голосов
/ 16 мая 2018

Согласно документации SciChart, SciChartSurface реализует шаблоны Finalizer и Dispose , которые вызывают удаление дочерних элементов при выгрузке диаграммы из памяти.

В документации также показано, что RenderSurface реализует Finalize , поэтому ресурсы должны автоматически очищаться, когда диаграмма больше не удерживается какими-либо объектами.

Если вы испытываете что-то другое, это, вероятно, ошибка.

Лучше всего проверить, используете ли вы последнюю версию SciChart из их канала NuGet , и после этого, если проблема все еще возникает, отправить отчет об ошибке с кодом для воспроизведения. ошибка в технической поддержке .

...