MediaElement throwing RPC_E_WRONG_THREAD

0

I'm trying to play a sound from my Windows Runtime Component during an event from a 3rd party hardware API, and it's turning out to be a lot more involved than I thought. When I try to instantiate a MediaElement I keep getting an exception with Message The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).

Looking around it seems that the fix for this is to call from the Dispatcher thread, but that doesn't even seem to be working. Right now my function looks like this:

private void PlayBeep()
{
    var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;

    dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        async () =>
        {
            MediaElement snd = new MediaElement();
            StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Sounds");
            StorageFile file = await folder.GetFileAsync("tada.wav");
            var stream = await file.OpenAsync(FileAccessMode.Read);
            snd.SetSource(stream, file.ContentType);
            snd.Play();
        });
    }
}

I also noticed that if I set a breakpoint inside and outside my anonymous function there, that both appear to be executing on a background thread, so perhaps the dispatcher isn't working like I think it is?

Outside anonymous function:

Thread.CurrentThread
{System.Threading.Thread}
    base: {System.Threading.Thread}
    ...
    IsAlive: true
    IsBackground: true
    IsThreadPoolThread: false
    ManagedThreadId: 1
    Name: null
    Priority: Normal
    ThreadState: Background

Inside anonymous function:

Thread.CurrentThread
{System.Threading.Thread}
    base: {System.Threading.Thread}
    ...
    IsAlive: true
    IsBackground: true
    IsThreadPoolThread: false
    ManagedThreadId: 1
    Name: null
    Priority: Normal
    ThreadState: Background
c#
windows-store-apps
dispatcher
mediaelement
asked on Stack Overflow Feb 27, 2014 by John

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0