gpt4 book ai didi

multithreading - 在可单元测试的 MVVM 代码中使用 Dispatcher

转载 作者:行者123 更新时间:2023-12-01 05:42:09 24 4
gpt4 key购买 nike

我有一个 MVVM-lite 应用程序,我想对其进行单元测试。该模型使用 System.Timers.Timer,因此更新事件在后台工作线程上结束。这个单元测试很好,但在运行时抛出 System.NotSupportedException “这种类型的 CollectionView 不支持从不同于 Dispatcher 线程的线程更改其 SourceCollection。”我曾希望 MVVM-lite 类 Threading.DispatcherHelper 能够解决问题,但调用 DispatcherHelper.CheckBeginInvokeOnUI 会导致我的单元测试失败。这是我在 View 模型中结束的代码

private void locationChangedHandler(object src, LocationChangedEventArgs e)
{
if (e.LocationName != this.CurrentPlaceName)
{
this.CurrentPlaceName = e.LocationName;
List<FileInfo> filesTaggedForHere = Tagger.FilesWithTag(this.CurrentPlaceName);

//This nextline fixes the threading error, but breaks it for unit tests
//GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(delegate { updateFilesIntendedForHere(filesTaggedForHere); });

if (Application.Current != null)
{
this.dispatcher.Invoke(new Action(delegate { updateFilesIntendedForHere(filesTaggedForHere); }));
}
else
{
updateFilesIntendedForHere(filesTaggedForHere);
}
}
}
private void updateFilesIntendedForHere(List<FileInfo> filesTaggedForHereIn)
{
this.FilesIntendedForHere.Clear();
foreach (FileInfo file in filesTaggedForHereIn)
{
if (!this.FilesIntendedForHere.Contains(file))
{
this.FilesIntendedForHere.Add(file);
}
}
}

我确实尝试过 http://kentb.blogspot.com/2009/04/mvvm-infrastructure-viewmodel.html 中的技巧但是在单元测试期间对 Dispatcher.CurrentDispatcher 的 Invoke 调用未能运行,因此失败。这就是为什么如果运行是在测试中而不是在应用程序中,我会直接调用辅助方法。

这不可能是正确的 - ViewModel 不应该关心从哪里调用它。谁能看出为什么 Kent Boogaart 的调度程序方法和 MVVM-lite DispatcherHelper.CheckBeginInvokeOnUI 在我的单元测试中都不起作用?

最佳答案

我这样做:

class MyViewModel() {
private readonly SynchronizationContext _syncContext;

public MyViewModel() {
_syncContext = SynchronizationContext.Current; // or use DI
)

...

public void SomeTimerEvent() {
_syncContext.Post(_ => UpdateUi(), null);
}
}

默认上下文将是您的测试中的线程池和 UI 中的调度程序。如果您想要一些其他行为,您还可以轻松创建自己的测试上下文。

关于multithreading - 在可单元测试的 MVVM 代码中使用 Dispatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4778380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com