[我们有一个带有ThreadPool
和WaitHandle
的旧应用程序。我们想针对它使用MSTest编写单元测试。我们遇到一个问题,默认情况下,MSTest在STA(单线程单元)模式下运行,并且测试抛出以下异常,
System.NotSupportedException:WaitAll用于STA上的多个句柄不支持线程。在System.Threading.WaitHandle.WaitMultiple(WaitHandle [] waitHandles,Int32毫秒超时,布尔值exitContext,布尔值WaitAll)在System.Threading.WaitHandle.WaitAll(WaitHandle [] waitHandles,Int32millisecondsTimeout,布尔值exitContext),位于System.Threading.WaitHandle.WaitAll(WaitHandle [] waitHandles,时间跨度超时,布尔值exitContext)
经过一段时间的研究,我们发现了如何将测试设置从STA更改为MTA。
[将test.runsettings
文件添加到解决方案的文件夹中
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<RunConfiguration>
<ExecutionThreadApartmentState>MTA</ExecutionThreadApartmentState>
</RunConfiguration>
</RunSettings>
编辑**.Test.csproj
文件并引用test.runsettings
文件,
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
...
<RunSettingsFilePath>$(SolutionDir)\test.runsettings</RunSettingsFilePath>
...
</PropertyGroup>
</Project> ```
Now run your test, it should work.