Open MediaPlayer - event unhandled in Thread

南笙酒味 提交于 2019-12-02 04:53:11

One thing is for certain: the Thread.Sleep call has nothing to do with your memory problem.

I would suggest that you clean up your code a little bit more. There's no need for you to be creating a new MediaCreator and a new MediaPlayer for every file you load. That could be a large part of the memory use, since you're creating all those MediaPlayer objects and not closing them. The garbage collector will eventually clean them up, but it can make your memory use look huge in the meantime.

Consider this:

public static void AddMediaFilesToMediaList()
{
    MediaFileCreator mfCreator = new MediaFileCreator();

    while (MediaFilesQueue.Count > 0)
    {
        // all the files are loaded into the Queue before processing
        string pathToFile = MediaFilesQueue.Dequeue();

        MediaFile mf = mfCreator.CreateNewMediaFile(pathToFile);

        MediaData.MediaList.Add(mf);
    }
}

public class MediaFileCreator
{
    private MediaPlayer player = new MediaPlayer();
    private ManualResetEvent openedEvent = new ManualResetEvent(false);

    public MediaFileCreator()
    {
        player.MediaOpened = MediaOpened;
    }

    private void MediaOpened(object sender, EventArgs args)
    {
        openedEvent.Set();
    }

    public MediaFile CreateNewMediaFile(string filename)
    {
        openedEvent.Reset();

        player.Open(new Uri(tempMediaFile.PathToFile));

        // wait for it to load
        openedEvent.WaitOne();

        MediaFile mf = new MediaFile(filename);
        mf.HasVideo = player.HasVideo;
        mf.HasAudio = player.HasAudio;
        mf.TimeSpanOfMediaFile = player.NaturalDuration.TimeSpan;

        player.Close();

        return mf;
    }
}

That simplifies things quite a bit and uses only one MediaPlayer object, which should cut down quite a bit on the memory usage.

I really don't know what the problem is with your AutoResetEvent not working. It looks right.

In this new code, you can put a breakpoint on the waitHandle.Set call to see if it's actually hit. I don't know when exactly the MediaOpened event is triggered, or what the state of the player is supposed to be when the event is raised. The documentation is suspiciously silent about that.

It's possible the problem is that MediaPlayer wants its code to be executing on the UI thread. I'm not familiar enough with the WPF controls to say. You might call VerifyAccess to determine if your thread has access to the object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!