c# - NUnit 异步测试 + RequiresSTA => 等待不在 STA 线程上返回

标签 c# wpf nunit async-await sta

下面的代码:

    [RequiresSTA]
    [Test]
    public async Task TestSta()
    {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId+" - "+Thread.CurrentThread.GetApartmentState());
        // *** await something here ***
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId+" - "+Thread.CurrentThread.GetApartmentState());
        new FrameworkElement();
    }

产生以下输出:

9 - STA

12 - MTA

然后,在 new FrameworkElement() 上抛出 InvalidOperationException。

NUnit 支持 STA 线程创建,现在支持异步测试,但它似乎没有通过创建 MTA SynchronizationContext 来混合这两种模式。

我如何让它工作?任何解决方法?

最佳答案

您可以使用 AsyncContext from my AsyncEx library ,在单元测试库支持它们之前,它最初是为了支持 async 单元测试而编写的。

[RequiresSTA]
[Test]
public Task TestSta()
{
  AsyncContext.Run(async () =>
  {
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId+" - "+Thread.CurrentThread.GetApartmentState());
    // *** await something here ***
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId+" - "+Thread.CurrentThread.GetApartmentState());
    new FrameworkElement();
  });
}

关于c# - NUnit 异步测试 + RequiresSTA => 等待不在 STA 线程上返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838116/

相关文章:

c# - xml序列化和编码

c# - C# 中的 Java SHA1 等效项

c# - 构造函数中的依赖关系日志的行为与注入(inject)到函数中的日志的行为不同

c# - 从堆栈面板的中心开始的元素

wpf - 与 ElementName 绑定(bind)不起作用

c# - 为 C++ DLL 实现回调 C# 函数

c# - WPF 使 ListView 高度与 Grid 行高相同

visual-studio-2012 - 如何将 NUnit 测试适配器与 NUnit 2.6.3 结合使用

c# - 如何在 C# 中加载我的测试数据?

.net - 为什么 NUnit 在命令行中挂起,但在 TestDriven.NET 下却没有挂起?