下面的代码:
[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/