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

标签 async-await .net-core xunit

在单个 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...");
    }
}

结果如下:
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...

进程似乎死锁,永远不会进行到预期的输出 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$

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

最佳答案

经过两天的纠缠 SynchronizationContext (基本上没有过多谈论“UI 线程”的最佳信息可以在这里找到:https://blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext-and-console-apps/)我明白发生了什么。
控制台应用程序不提供任何 SynchronizationContext ,因此 CLR 会将任务卸载到线程池上的线程。无论机器有什么 CPU,都有足够的可用线程。一切正常。
xunit 确实提供了一个 Xunit.Sdk.MaxConcurrencySyncContext主动管理正在运行的线程数量。最大并发级别默认为您拥有的逻辑 CPU 数量,但是,它可以是 configured .运行测试的线程已经达到这个限制,所以任务完成被阻塞。
所有这些都是为了重现一个更复杂的 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();
    }
}
虽然在 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");
                    }
                });
在我的(8 个逻辑 CPU)机器上,它工作正常,在单个 CPU 网络主机上它工作正常,但单个 CPU 上的 xunit 死锁。如果您仔细阅读 CancellationToken 的文档什么ApplicationStarted实际上是,你会发现:

The current System.Threading.ExecutionContext, if one exists, will be captured along with the delegate and will be used when executing it.


将此与 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");
                    }
                });

关于async-await - 为什么这个 xunit 测试死锁(在单个 CPU 虚拟机上)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50918647/

相关文章:

c# - 解决 .Net core 2.0 中抽象类的依赖注入(inject)

nunit - 我可以围绕 NUnit、MbUnit、xUnit 或其他测试框架创建包装器吗?

c# - 使用.Net 6动态读取.Net core Web App中的Azure应用程序配置

asp.net-core - .NET Core 静态代码分析工具

task-parallel-library - I/O 性能 - 异步 vs TPL vs Dataflow vs RX

c# - C# 中的 Promise 等价物

c# - xUnit 测试引擎的 InlineDataAttribute + 可选方法参数

ASP.NET MVC : testing a controller with XUnit

javascript - 从对象创建异步 waterfall

c# - 实现 AsyncCodeActivities(使用 C# async/await)