Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RaiseCanExecuteChanged COM Exception during Navigation?

Update

Uploaded sample project: https://github.com/subt13/BugSamples

I have reproduced an error that has been occurring in a Windows 10 UAP application that utilizes the MVVMLight framework.

I receive the error below during navigation while the CPU is under heavy load (~20-25%) and the page is "heavy" (large images, lots of controls, etc., etc.)

at System.Runtime.InteropServices.WindowsRuntime.ICommandAdapterHelpers.<>c__DisplayClass2.b__3(Object sender, EventArgs e) at System.EventHandler.Invoke(Object sender, EventArgs e) at GalaSoft.MvvmLight.Command.RelayCommand.RaiseCanExecuteChanged() at RaiseExecuteChangeRepo.ViewModel.MainViewModel.d__17.MoveNext()

In the sample, the error occurs on RaiseCanExecuteChanged();

    private async void ExecuteLoadDataCommandAsync()
    {
        // cause the app to slow done.
        var data = await Task.Run(() => GetData()); 

        if (data != null)
        {
            this.Data.Clear();

            foreach (var item in data)
            {
                this.Data.Add(new AnotherVM(item));
            }
        }

        // have the select job command rerun its condition
        this.SelectCommand.RaiseCanExecuteChanged();
    }

    // slow down the page
    public List<DataItem> GetData()
    {
        var myList = new List<DataItem>();
        for (int i = 0; i < 100000; ++i)
        {
            myList.Add(new DataItem("Welcome to MVVM Light"));

        }

        return myList;
    }

Nothing special is happening during navigation other than the command associated with ExecuteLoadDataCommandAsync() is getting called to load data.

<Core:EventTriggerBehavior EventName="Loaded">
    <Core:InvokeCommandAction Command="{Binding LoadDataCommand}">
   </Core:InvokeCommandAction>
</Core:EventTriggerBehavior>

To reproduce, simply toggle from one page to the other rapidly for a few seconds and then just wait. After not too long the exception will be raised.

like image 781
O.O Avatar asked Sep 16 '15 19:09

O.O


1 Answers

I ended up fixing my issue by adding the following event to the code behind.

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    this.DataContext = null;
    base.OnNavigatedFrom(e);
}
like image 148
O.O Avatar answered Oct 06 '22 00:10

O.O