2

asyncCtpでDPの使用法をテストするために、いくつかのサンプルViewModelを作成しました。

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;
    }
}

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 

それで、解決策は何ですか?

4

1 に答える 1

1

まず、Microsoft.Bcl.Asyncパッケージを使用してVS2012にアップグレードすることをお勧めします。これにより、最新のツールを使用して.NET4.0をターゲットにすることができます。Async CTPには修正されない既知のバグがあり、インストールの問題(修正されない)があり、新しい開発マシンのセットアップが非常に困難になります。

ただし、非同期CTPを削除する前に、(C# Testing) Unit Testing非同期CTPディレクトリの下のディレクトリを確認してください。ユニットテストに役立ついくつかのタイプがあります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);
}
于 2012-12-09T13:36:44.550 に答える