【发布时间】:2017-02-09 20:06:01
【问题描述】:
当我像这样锁定 ThreadPool 上的线程时,线程被阻塞:
private static object _testServerLock = new object();
private static TestServer _testServer = null;
public TestServer GetServer()
{
lock (_testServerLock)
{
if (_testServer == null)
{
_testServer = new TestServer(); // does some async stuff internally
}
}
return _testServer;
}
如果调用它的并发线程多于 ThreadPool 中的线程,所有线程最终都会等待锁定,而其他地方发生的异步代码无法继续,因为它正在等待 ThreadPool 中的空闲线程.
所以我不想阻塞线程,我需要在等待时将其返回到 ThreadPool。
是否有其他方法可以锁定将等待线程返回到 ThreadPool?
【问题讨论】:
-
您考虑过使用 xUnit 的“类夹具”吗? xunit.github.io/docs/shared-context.html 您可以使用它与测试类中的所有测试共享 TestServer 实例。或者如果您想跨测试类共享上下文,也可以选择共享上下文
-
xunit 将默认为每个测试类创建一个夹具,这是我的夹具共享的静态资源,它应该只存在一次。而且我想并行运行测试,否则这将需要很长时间。
-
xUnit 根本不直接提供类似的东西(这是一般花瓶中一团糟的秘诀)。为了引起足够的并行性,下面指出了方法-您需要足够的并发测试类[不受同一个测试集合的约束],然后将
asyncness 从资源传播到测试方法签名,方法是使每个一个Task<T>,但没有任何Waits
标签: asp.net-core locking threadpool xunit.net