aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

TestServer blocks on HostedService asyncronous background threads

Open sjlangleyCSGI opened this issue 7 years ago • 5 comments

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:

  1. Using: ASP.NET Core '2.1', XUnit 2.4, and Microsoft.AspNetCore.Mvc.Testing 2.1.3
  2. In service's Startup.cs: In ConfigureServices(IServiceCollection services): services.AddHostedService(); In IHostedService.StartAync() <- infinite loop for background work
  3. 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

sjlangleyCSGI avatar Jan 04 '19 20:01 sjlangleyCSGI

Possibly by design. Return the Task or Execute and return Task.CompletedTask

dcarr42 avatar Jan 04 '19 22:01 dcarr42

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

davidfowl avatar Jan 05 '19 04:01 davidfowl

Also we plan to address the blocking by firing a background thread pool thread which should never block

davidfowl avatar Jan 05 '19 04:01 davidfowl

So why the difference in behavior with Kestrel?

sjlangleyCSGI avatar Jan 07 '19 15:01 sjlangleyCSGI

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.

aspnet-hello avatar Mar 11 '19 17:03 aspnet-hello