gpt4 book ai didi

c# - 将依赖属性与异步 ctp 一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 13:50:42 25 4
gpt4 key购买 nike

我已经创建了一些示例 ViewModel 来测试 DPs 与 asyncCtp 的使用情况:

public class SampleVm : DependencyObject
{

public static readonly DependencyProperty SampleDependencyPropertyProperty =
DependencyProperty.Register("SampleDependencyProperty", typeof (int), typeof (SampleVm), new PropertyMetadata(default(int)));

public int SampleDependencyProperty
{
get { return (int) GetValue(SampleDependencyPropertyProperty); }
set { SetValue(SampleDependencyPropertyProperty, value); }
}
public ISampleModel _model;
public SampleVm(ISampleModel model)
{
_model = model;
}

public async Task SetDependencyProperty()
{
var modelData = await TaskEx.Run(() => _model.GetSomeIntegerValue());
SampleDependencyProperty = modelData;
}
}

注入(inject)到 ViewModel 的模型是:

public interface ISampleModel
{
int GetSomeIntegerValue();
}

public class SampleModel : ISampleModel
{
public int GetSomeIntegerValue()
{
return 10;
}
}

当我运行 WPF 应用程序时没有问题,但是当我想用下面的代码测试它时:

[Fact]
public async Task CheckValueSetting()
{
var model = new Mock<ISampleModel>();
model.Setup(x => x.GetSomeIntegerValue()).Returns(5);
var viewModel =new SampleVm(model.Object);

await viewModel.SetDependencyProperty();

Assert.Equal(5, viewModel.SampleDependencyProperty);
}

我收到以下错误:

System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it.

Server stack trace:

at System.Windows.Threading.Dispatcher.VerifyAccess()
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
at WpfApplication4.SampleVm.set_SampleDependencyProperty(Int32 value) in SampleVM.cs: line 19
at WpfApplication4.SampleVm.<SetDependencyProperty>d__1.MoveNext() in SampleVM.cs: line 30

Exception rethrown at [0]:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at WpfApplication4.SampleVmFixture.<CheckValueSetting>d__0.MoveNext() in SampleVmFixture.cs: line 16

那么解决方案是什么?

最佳答案

首先,我建议您使用 Microsoft.Bcl.Async package 升级到 VS2012 .这将使您能够使用最新的工具以 .NET 4.0 为目标。 Async CTP 具有无法修复的已知错误,并且存在安装问题(无法修复),这将使设置新的开发机器变得非常困难。

但在删除 Async CTP 之前,请检查 Async CTP 目录下的 (C# Testing) Unit Testing 目录。您会发现多种有助于单元测试的类型,例如 GeneralThreadAffineContext:

[Fact]
public async Task CheckValueSetting()
{
var model = new Mock<ISampleModel>();
model.Setup(x => x.GetSomeIntegerValue()).Returns(5);
SampleVm viewModel;
await GeneralThreadAffineContext.Run(async () =>
{
viewModel = new SampleVm(model.Object);
await viewModel.SetDependencyProperty();
});

Assert.Equal(5, viewModel.SampleDependencyProperty);
}

关于c# - 将依赖属性与异步 ctp 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13785849/

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