MediaElement抛出RPC_E_WRONG_THREAD

时间:2014-02-27 22:27:33

标签: c# windows-store-apps dispatcher mediaelement

我正试图在来自第三方硬件API的事件中播放来自我的Windows运行时组件的声音,并且它比我想象的要多得多。当我尝试实例化MediaElement时,我不断收到消息The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))的异常。

环顾四周似乎解决这个问题的方法是从Dispatcher线程调用,但这似乎不起作用。现在我的功能看起来像这样:

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();
        });
    }
}

我还注意到,如果我在我的匿名函数内部和外部设置断点,那么两者似乎都在后台线程上执行,那么调度程序可能不像我想的那样工作?

外部匿名功能:

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

匿名函数内部:

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

0 个答案:

没有答案