如何避免我的.net应用程序中的内存泄漏(使用VLC)

时间:2017-03-11 15:08:16

标签: c# .net wpf memory-leaks

我正在构建一个数字标牌应用程序。我需要显示混合的图像和视频(3个图像,然后是视频 - 然后重复此操作)。我正在使用WPF应用程序。我在WPF中使用“MediaElement”运气不好 - 我有一些无法播放的文件(在某些情况下甚至是默认的“wildlife.wmv”文件)。我转向VLC,现在我的应用程序只运行了大约3个小时,然后我的内存不足/我的vlc播放器变黑了。

我在Windows窗体组件中包含了一个VLC组件。然后将Windows窗体组件添加到我的WPF应用程序中。

我的代码如下所示。我使用反射加载它 - 我发现这使用最少的内存。几个小时以来一直在这里。

//code
 string path = Assembly.GetExecutingAssembly().Location;
 string directory = new System.IO.FileInfo(path).Directory.FullName;
 string newPath = System.IO.Path.Combine(directory, "MedianVLCLibrary.dll");
 if (System.IO.File.Exists(newPath))
 {
   Assembly vlcAssembly = Assembly.LoadFrom(newPath);
   myVlcType = vlcAssembly.GetType("MedianVLCLibrary.VLCUserControl");
 }
 else
 {
   MedianLog.Log.Instance.LogFatal("Could not fild MedianVLCLibrary.dll");
   throw new FileNotFoundException(newPath);
 }
 obj = Activator.CreateInstance(myVlcType);
 this.presentationGrid.Children.Add((UIElement)obj); //adding the ui element to the WPF grid
 MethodInfo playMethod = myVlcType.GetMethod("Play");
 playMethod.Invoke(obj, new object[] { file });
 EventInfo completedEvent = myVlcType.GetEvent("PlayCompleted");
 Delegate completedDelegate = Delegate.CreateDelegate(completedEvent.EventHandlerType, this, "PlayerCompleted");

completedEvent.AddEventHandler(obj,completedDelegate);

然后在我调用回调方法之前,在我的“PlayComplete”方法中进行清理。

obj = null;
myVlcType = null;
vlcAssembly = null;
this.presentationGrid.Children.Clear();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
FinishedCallback();

我使用在线发现的样本制作了VLC包装器。请参阅下面的代码。

 public partial class VLCUserControl : UserControl, IDisposable
    {
        AxVLCPlugin2 vlc;
        public VLCUserControl()
        {
            InitializeComponent();
            vlc = new AxVLCPlugin2();
            vlc.BeginInit();
            windowsFormsHost.Child = vlc;
            vlc.EndInit();
        }

        public void Play(string path)
        {
            var uri = new Uri(path);
            var convertedURI = uri.AbsoluteUri;
            vlc.playlist.add(convertedURI, null, null);
            vlc.playlist.play();
            vlc.MediaPlayerEndReached += Vlc_MediaPlayerEndReached;
        }

        private void Vlc_MediaPlayerEndReached(object sender, EventArgs e)
        {
            vlc.playlist.items.clear();
            vlc.MediaPlayerEndReached -= Vlc_MediaPlayerEndReached;
            if (PlayCompleted != null)
            {
                PlayCompleted();
            }           
            //vlc = null;
            GC.Collect();
        }

        public void Dispose()
        {
            vlc.Dispose();
        }

        public event Action PlayCompleted;
    }

0 个答案:

没有答案