【问题标题】:Thread exception when using Messages使用消息时的线程异常
【发布时间】:2014-11-03 10:01:52
【问题描述】:

在我的 ViewModel 构造函数中的 Windows Phone 应用程序中,我像这样注册了一个信使:

Messenger.Default.Register<MyType>
(
    this,
    (action) => ReceiveMessage(action)
);

然后在 ReceiveMessage 中我尝试输入一些代码,然后它崩溃了

"The application called an interface that was marshalled for a different thread."

private void ReceiveMessage(MyType action)
{
    this.MyCollection.Clear();

    foreach (Student st in Students)
    {
        this.MyCollection.Add(st);
    }
}

我试过这样做,结果是一样的:

Application.Current.Resources.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.MyCollection.Clear());

【问题讨论】:

    标签: c# multithreading mvvm notifications messages


    【解决方案1】:

    您需要将对Dispatcher.RunAsync() 的调用放在注册的处理程序中,以便调用对ReceiveMessage() 的整个调用,而不仅仅是该方法的一个语句。

    Messenger.Default.Register<MyType>
    (
        this,
        (action) => Application.Current.Resources.Dispatcher.RunAsync(
            CoreDispatcherPriority.Normal, () => ReceiveMessage(action))
    );
    

    当然,将您的 ReceiveMessage() 方法改回原来的方式(没有调度程序调用)。

    另外,我不相信资源中的调度程序是正确的。这当然不是我在 WinRT 中所做的。也许这是电话问题,但如果上述方法仍然不起作用,请尝试改用 Application.Current.Dispatcher

    【讨论】:

    • 什么是堆栈跟踪?调用Register&lt;T&gt;() 方法时使用的是什么线程?你试过Application.Current.Dispatcher吗?还是在电话的Application 类中不可用?
    猜你喜欢
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多