c# - 导航期间出现 RaiseCanExecuteChanged COM 异常?

标签 c# windows-runtime async-await mvvm-light win-universal-app

更新

上传的示例项目:https://github.com/subt13/BugSamples

我重现了一个在使用 MVVMLight 框架的 Windows 10 UAP 应用程序中发生的错误。

当 CPU 处于高负载 (~20-25%) 并且页面“很重”(大图像、大量控件等)时,我在导航期间收到以下错误

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

在示例中,错误发生在 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;
    }

除了调用与 ExecuteLoadDataCommandAsync() 关联的命令来加载数据外,在导航期间没有发生任何特殊情况。

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

要重现,只需从一页快速切换到另一页几秒钟,然后等待即可。不久之后将引发异常。

最佳答案

我最终通过将以下事件添加到后面的代码来解决我的问题。

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    this.DataContext = null;
    base.OnNavigatedFrom(e);
}

关于c# - 导航期间出现 RaiseCanExecuteChanged COM 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32617189/

相关文章:

c# - 将新对象添加到 DbContext 时 Entity Framework 中出现空引用异常

c# - 使用 DataReader 读取数百万数据时,如何避免数据库连接丢失问题?

c# - 将 IEnumerable.Aggregate 与异步调用结合使用

c# - 从以 Task 为返回类型的非异步方法返回什么?

c# - 使用异步 lambda 运行任务

c# - 线程安全事件 - 这是 "clean"方式吗?

c# - LINQ查询错误中的匿名函数

c# - DataGrid 的 WinRT 端口中的神秘 "Not enough quota is available to process this command"

windows-runtime - 用于 WinRT 的 QrCode 开源库

c# - Windows 8 应用程序使用 Xaml 和 C# 以适应不同的屏幕尺寸和 DPI?