2016-03-08 167 views
0

我正在使用MediaElement長時間顯示循環中的視頻剪輯。經過一段時間(Win 7/4 GB RAM的小時),程序崩潰,但「內存不足」類型除外。我監視使用Process Explorer-Sysinternals時使用的內存,並使用System.Diagnostics.Process方法記錄它。兩種方式都表明使用內存逐漸增加。如何釋放MediaElement使用的內存

下面是代碼:

XAML:

<Grid Name="GridTest"> 
    <MediaElement x:Name="MediaPlayer" 
        LoadedBehavior="Manual" 
        MediaEnded="VideoControl_MediaEnded" 
        MediaOpened="MediaPlayer_MediaOpened" 
        Source="{Binding Mode=OneWay, 
            Path=MySource}" /> 
</Grid> 

的.cs:

public partial class MainWindow : Window 
{ 
    public MainViewModel model = new MainViewModel(); 

    public MainWindow() 
    { 
     InitializeComponent(); 

     this.GridTest.DataContext = model; 

     // fill in model.MediaFilesUris: 
     ... 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     // choose the next media file 
     ... 

     MediaPlayer.Play(); 
    } 

    private void VideoControl_MediaEnded(object sender, RoutedEventArgs e) 
    { 
     // choose the next media file 
     ... 

     model.OnPropertyChanged("MySource"); 

     MediaPlayer.Play(); 
    } 
} 


public class MainViewModel : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    public void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 

    public Uri[] MediaFilesUris = null; 
    public int crn = 0; 

    public Uri MySource { get { if (MediaFilesUris != null && MediaFilesUris.Count()>0) return MediaFilesUris[crn]; else return null; } } 

} 

我還測試的情況下的MediaElement對象是動態創建的,與所有破壞(一起取消訂閱活動等),然後重新創建。記憶力再次被消耗。

任何建議,將不勝感激!

+0

你是如何 「毀」 你的MediaElement?這是一個UI元素,WPF爲UI元素做了一件糟糕的工作。 – Xcalibur37

+0

試圖在遊戲結束時使Source = null?你明確地試試。 – EngineerSpock

+0

下面是我如何「銷燬」MediaElement obejct(以編程方式創建,而不是在XAML中):MediaPlayer.Stop(); MediaPlayer.MediaEnded - = MediaPlayer_MediaEnded; MediaPlayer.MediaOpened - = MediaPlayer_MediaOpened; MediaPlayer.Close(); GridTest.Children.Remove(MediaPlayer); MediaPlayer = null; GC.Collect(); 如果使用綁定Source屬性創建,也在Close()之前創建:BindingOperations.ClearBinding(MediaPlayer,MediaElement.SourceProperty); – MDimitrov

回答

0

我的建議是做以下:

private void VideoControl_MediaEnded(object sender, RoutedEventArgs e) 
{ 
    // choose the next media file 
    ... 
    //make the following explicitly 
    MediaPlayer.Stop();  
    MediaPlayer.Source = null; 

    model.OnPropertyChanged("MySource"); 

    MediaPlayer.Play(); 
} 
+0

也試過MediaPlayer.Stop(); MediaPlayer.Source = null; MediaPlayer.Close();然後在VideoControl_MediaEnded()中重新分配Source,但不起作用。 – MDimitrov

+0

@MDimitrov嗯,你也可以嘗試爲整個MediaPlayer對象分配null,然後重新實例化它。 – EngineerSpock

+0

我也這樣做了,在上面的評論中寫了一篇關於如何「銷燬」對象的評論 – MDimitrov