TestServer blocks on HostedService asyncronous background threads
A .NET Core 2.1 TestServer instance which adds a HostedService (with an infinite loop) at startup blocks on that thread instead of running it asynchronously.
To Reproduce
Steps to reproduce the behavior:
- Using: ASP.NET Core '2.1', XUnit 2.4, and Microsoft.AspNetCore.Mvc.Testing 2.1.3
- In service's Startup.cs:
In ConfigureServices(IServiceCollection services):
services.AddHostedService
(); In IHostedService.StartAync() <- infinite loop for background work - In Test project, create instance of TestServer using service's IWebHostBuilder and execute tests against service
Expected behavior
Tests should execute, but instead the tests hang as the service never completes starting up.
I suspect that TestServer is awaiting IHostedService.StartAsync. Have a workaround by refactoring IHostedService's StartAsync to return immediately calling another async method to perform work. Example:
//hangs in TestSever instance public async Task StartAsync(CancellationToken cancellationToken) { //infinite loop }
//works in TestServer instance public async Task StartAsync(CancellationToken cancellationToken) { DoTheWork(cancellationToken); } public async Task DoTheWork(CancellationToken cancellationToken) { //infinite loop }
Additional context
Does not effect Kestrel server, only TestServer
Possibly by design. Return the Task or Execute and return Task.CompletedTask
Yes this is by design StartAsync is to kick off asynchronous work, not hang forever. To write a long running asynchronous loop, use the BackgroundService base class
Also we plan to address the blocking by firing a background thread pool thread which should never block
So why the difference in behavior with Kestrel?
We periodically close 'discussion' issues that have not been updated in a long period of time.
We apologize if this causes any inconvenience. We ask that if you are still encountering an issue, please log a new issue with updated information and we will investigate.