Search code examples
c#.net-coredependency-injection.net-5idisposable

DisposeAsync method deadlocks when shutting down a .NET Core App


In my .NET 5 console app I have a class that implements IAsyncDisposable, because it needs to call an async shutdown method of a third-party library, something like this:

    public async ValueTask DisposeAsync()
   {
        await thirdParyLib.ShutDownAsync();
   }

This works without issues when using the class with the classic using statement.

However, when I register the class in .NET Core's Dependency Injection mechanism (as a singleton), I'm having problems.

In particular, when the .NET Core application stops the DI framework automatically (and correctly) calls DisposeAsync() on all singleton instances that are registered. This would be perfect, but the problem is that at that point the code hangs here:

await thirdParyLib.ShutDownAsync();

I'm assuming the thread is deadlocked, but I don't know how to further diagnose and solve the problem. Any ideas?


Solution

  • Well, I found the solution in my specific case, which was to directly call Dispose() on the third-party object, rather than the dedicated async method that was being problematic.