为什么这个 xunit 测试死锁(在单个 CPU 虚拟机上)?

Mar*_*tke 5 xunit async-await .net-core

在单个 CPU VM (Ubuntu 18.4) 上运行以下测试

using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

public class AsyncStuffTest
{
    [Fact]
    public void AsyncTest()
    {
        SomethingAsync().Wait();
    }

    private static async Task SomethingAsync()
    {
        Console.WriteLine("before async loop...");
        await Task.Factory.StartNew(() => {
                                        for (int i = 0; i < 10; i++)
                                        {
                                            Console.WriteLine("in async loop...");
                                            Thread.Sleep(500);     
                                        }
                                    });
        Console.WriteLine("after async loop...");
    }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

Build started, please wait...
Build completed.

Test run for /home/agent/fancypants/bin/Debug/netcoreapp2.1/fancypants.dll(.NETCoreApp,Version=v2.1)
Microsoft (R) Test Execution Command Line Tool Version 15.7.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
before async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
Run Code Online (Sandbox Code Playgroud)

进程似乎陷入僵局,永远不会进行到预期的输出 after async loop...

在我的开发机器上运行一切正常。

注意:我知道在 xunit 中进行异步测试的可能性。这或多或少是一个令人感兴趣的问题。特别是因为这个问题只影响 xunit,控制台应用程序终止正常:

~/fancypants2$ dotnet run
before async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
in async loop...
after async loop...
~/fancypants2$
Run Code Online (Sandbox Code Playgroud)

更新:阅读一些与 xunit 中异步相关的最新修复,所以我在 2.4.0-beta.2.build4010 中尝试了这个,但没有任何变化。

Mar*_*tke 10

经过两天的思考SynchronizationContext(基本上没有过多谈论“UI 线程”的最佳信息可以在这里找到:https : //blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext -and-console-apps/ ) 我明白发生了什么。

控制台应用程序不提供任何SynchronizationContext,因此 CLR 会将任务卸载到线程池上的线程。无论机器有什么 CPU,都有足够的线程可用。一切正常。

xunit 确实提供了一个Xunit.Sdk.MaxConcurrencySyncContext主动管理正在运行的线程数量的方法。最大并发级别默认为您拥有的逻辑 CPU 数量,但是,它可以配置。运行测试的线程已经达到这个限制,所以任务完成被阻塞。

所有这些都是为了重现一个更复杂的 ASP.Net Core Web 应用程序的问题,该应用程序在提到的单个 CPU 构建代理上表现得很奇怪。集成测试使用一个集合范围的共享夹具来启动一个TestServer

public class ServiceHostFixture : IAsyncLifetime
{
    public async Task InitializeAsync()
    {
        IWebHostBuilder host = new WebHostBuilder()
                    .UseEnvironment("Production")
                    .UseStartup<Startup>();

        Server = new TestServer(host);
    }

    public async Task DisposeAsync()
    {
        Server.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然有一个有趣的地方Startup.Configure(IApplicationBuilder app)

app.ApplicationServices
    .GetRequiredService<IApplicationLifetime>()
    .ApplicationStarted
    .Register(async () => {
                    try
                    {
                        // it blocks here in xunit
                        await EnsureSomeBasicStuffExistenceInTheDatabaseAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.Fatal(ex, "Application could not be started");
                    }
                });
Run Code Online (Sandbox Code Playgroud)

在我的(8 个逻辑 CPU)机器上,它工作正常,在单个 CPU 网络主机上它工作正常,但单个 CPU 上的 xunit 死锁。如果你读的仔细文档CancellationToken什么ApplicationStarted其实是,你会发现这一点:

当前System.Threading.ExecutionContext,如果存在,将与委托一起被捕获并在执行时使用。

将此与 ASP.Net Core 和 xunit 之间的差异相结合,揭示了问题所在。我所做的是以下解决方法:

app.ApplicationServices
    .GetRequiredService<IApplicationLifetime>()
    .ApplicationStarted
    .Register(async () => {
                    try
                    {
                        if (SynchronizationContext.Current == null)
                        {
                            // normal ASP.Net Core environment does not have a synchronization context, 
                            // no problem with await here, it will be executed on the thread pool
                            await EnsureSomeBasicStuffExistenceInTheDatabaseAsync;
                        }
                        else
                        {
                            // xunit uses it's own SynchronizationContext that allows a maximum thread count
                            // equal to the logical cpu count (that is 1 on our single cpu build agents). So
                            // when we're trying to await something here, the task get's scheduled to xunit's 
                            // synchronization context, which is already at it's limit running the test thread
                            // so we end up in a deadlock here.
                            // solution is to run the await explicitly on the thread pool by using Task.Run
                            Task.Run(() => EnsureSomeBasicStuffExistenceInTheDatabaseAsync()).Wait();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Fatal(ex, "Application could not be started");
                    }
                });
Run Code Online (Sandbox Code Playgroud)