The application called an interface that was marsh

2019-07-21 21:13发布

I have a public timer and in its Tick event I send a message to my ViewModel. I start the timer from a button somewhere in my application. The problem is there is an exception when the ViewModel tries to register (using MVVM Light):

"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"

Here is the timer

public static class SomeManager
{
    private static Timer gAppTimer;
    private static object lockObject = new object();

    public static void StartTimer()
    {
        if (gAppTimer == null)
        {
            lock (lockObject)
            {
                if (gAppTimer == null)
                {
                    gAppTimer = new Timer(OnTimerTick, null, 10000, 10000);
                }
            }
        }
    }

    public static void StopTimer()
    {
        if (gAppTimer != null)
        {
            lock (lockObject)
            {
                if (gAppTimer != null)
                {
                    gAppTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    gAppTimer = null;
                }
            }
        }
    }

    private static void OnTimerTick(object state)
    {
        Action();
    }

    public static void Action()
    {
        GlobalDeclarations.GlobalDataSource.Clear();

        Messenger.Default.Send<ObservableCollection<PersonVMWrapper>>(GlobalDeclarations.GlobalDataSource);
    }
}

And here is the ViewModel:

public class PersonVM : INotifyPropertyChanged
{
    ....

    public PersonVM()
    {
        Messenger.Default.Register<ObservableCollection<PersonVMWrapper>>
        (
            this,
            (action) => ReceiveMessage(action)
        );
    }

    private void ReceiveMessage(ObservableCollection<PersonVMWrapper> action)
    {
        foreach (PersonVMWrapper pvmw in action)
        {
            DataSource.Add(pvmw);
        }
    }

    ...

1条回答
Lonely孤独者°
2楼-- · 2019-07-21 21:32

If your ObservableCollection is bound to a control, you can add or remove values only from the UI thread.

For this, you can use the DispatcherHelper class provided by the MVVM Light Toolkit:

DispatcherHelper.CheckBeginInvokeOnUI(
    () =>
    {
        foreach (PersonVMWrapper pvmw in action)
        { 
            DataSource.Add(pvmw);
        }
    });

It's also possible to call directly the dispatcher without using the MVVM Light Toolkit:

Deployment.Current.Dispatcher.BeginInvoke(
    () =>
    {
        foreach (PersonVMWrapper pvmw in action)
        { 
            DataSource.Add(pvmw);
        }
    });
查看更多
登录 后发表回答