Windows Desktop MediaPlayer Dispose Issue
Summary
After playback reaches to end, mp.Dispose() crashes.
Code Lines
//Variables
private PlayListItem listItem;
private LibVLC libVlc;
private Media media;
private MediaPlayer mp;
//Constructor
public frmVlcLibPlayer(PlayListItem file)
{
InitializeComponent();
listItem = file;
Core.Initialize();
libVlc = new LibVLC();
libVlc.CloseLogFile();
libVlc.ClearLibVLCError();
trackVolume.ValueChanged += TrackVolume_ValueChanged;
this.Shown += FrmVlcLibPlayer_Shown;
this.Closed += FrmVlcLibPlayer_Closed;
}
//Form Shown Event
private void FrmVlcLibPlayer_Shown(object sender, EventArgs e)
{
media = new Media(libVlc, listItem.Path);
Play();
}
//Video Play Method
public void Play()
{
videoPanel.Visible = true;
videoPanel.BringToFront();
if (mp == null)
{
mp = new MediaPlayer(media);
mp.EnableMouseInput = false;
mp.EnableKeyInput = false;
mp.Stopped += Mp_Stopped;
}
mp.Volume = listItem.Volume;
if (trackVolume.InvokeRequired)
{
trackVolume.Invoke((MethodInvoker)delegate { trackVolume.EditValue = mp.Volume; });
}
else trackVolume.EditValue = mp.Volume;
controlPanel.Visible = false;
controlPanel.SendToBack();
mp.Hwnd = videoPanel.Handle;
mp.Play();
media.Dispose();
}
//MediaPlayer Stopped Event
private void Mp_Stopped(object sender, EventArgs e)
{
mp.Stopped -= Mp_Stopped;
//Form Close call events...
}
//Form Closed Event
private void FrmVlcLibPlayer_Closed(object sender, EventArgs e)
{
if (mp != null)
{
if(mp.IsPlaying) mp.Stop();
**mp.Dispose();** This line is crashing...
}
if (libVlc != null)
{
libVlc.Dispose();
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
### Environment
- OS: Windows
- Version: 1803
- OS Build: 17134.950
- Device: Desktop
- Application Platform: Winform
- LibVLC version and architecture x86
- LibVLCSharp version 3.2.0
Possible fixes
I found a solution in my way, it is working with this change, i think this may need to bug fix... cus when i call mp.Dispose() method after 1sec. it is working properly
private void Mp_Stopped(object sender, EventArgs e)
{
mp.Stopped -= Mp_Stopped;
mp.Media.Dispose();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
Task.Factory.StartNew(() => Thread.Sleep(1000))
.ContinueWith((t) =>
{
//Form Close call events...
}, TaskScheduler.FromCurrentSynchronizationContext());
}