Npgsql throws exception if return a Task without await?

Problem: if you return from the handler Task without using async/await, the app crashes with this exception:
System.NullReferenceException: Object reference not set to an instance of an object.
 at Npgsql.ConnectorPool.Release(NpgsqlConnector connector) in C:\projects\npgsql\src\Npgsql\ConnectorPool.cs:line 446
 at Npgsql.NpgsqlConnection.Close(Boolean wasBroken) in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 630
 at Npgsql.NpgsqlConnection.Close() in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 615
 at Npgsql.NpgsqlConnection.Dispose(Boolean disposing) in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 670
 at System.ComponentModel.Component.Dispose()
 at SomeApp.Application.UseCases.ListLanguagesHandler.HandleAsync(ListLanguages userCase, CancellationToken cancellationToken) in /Volumes/Data/Workspace/Coding/SomeApp/Backend/SomeApp.Application/UseCases/ListLanguages.cs:line 45
 at SomeApp.Application.UseCaseDispatcher.HandleAsync[TUseCase,TResult](TUseCase useCase, CancellationToken cancellationToken) in /Volumes/Data/Workspace/Coding/SomeApp/Backend/SomeApp.Application/UseCaseDispatcher.cs:line 42
 at SomeApp.Startup.<>c.<<ConfigureV1Routes>b__4_4>d.MoveNext() in /Volumes/Data/Workspace/Coding/SomeApp/Backend/SomeApp/Startup.cs:line 67
--- End of stack trace from previous location where exception was thrown ---
 at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
 at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
 at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 0 ms 37953.763``


Question: why is this happening?
March 23rd 20 at 18:46
1 answer
March 23rd 20 at 18:48
Solution
Keywords async/await in this case is needed because the query to the database is happening inside the construction using. Since operation is asynchronous, the connection will be closed before the operation completed.

Find more questions by tags C#