O.O*_*O.O 9 c# mvvm-light async-await windows-runtime 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),位于RaiseExecuteChangeRepo的GalaSoft.MvvmLight.Command.RelayCommand.RaiseCanExecuteChanged()的System.EventHandler.Invoke(Object sender,EventArgs e) .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;
}
Run Code Online (Sandbox Code Playgroud)
除了与之相关的命令ExecuteLoadDataCommandAsync()被调用以加载数据之外,在导航期间没有发生任何特殊情况.
<Core:EventTriggerBehavior EventName="Loaded">
<Core:InvokeCommandAction Command="{Binding LoadDataCommand}">
</Core:InvokeCommandAction>
</Core:EventTriggerBehavior>
Run Code Online (Sandbox Code Playgroud)
要重现,只需从一个页面快速切换到另一个页面几秒钟,然后等待.不久之后,将引发异常.
我最终通过将以下事件添加到后面的代码中来解决我的问题。
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.DataContext = null;
base.OnNavigatedFrom(e);
}
Run Code Online (Sandbox Code Playgroud)