The .NET garbage collector (GC) does an excellent job of cleaning up unused resources and reclaiming memory once it is no longer needed. Unfortunately, it can only determine when a managed resource is no longer needed but not an unmanaged one.

Even if you don’t use unmanaged resources directly or don’t even know what the word “unmanaged” means, many of .NET’s built-in classes use unmanaged resources under the hood such as those around network communication (System.Net), streams and file handling (System.IO), image manipulation (System.Drawing), and cryptography.

What Happens if You Don’t Properly Dispose of Unmanaged Resources?

Assuming you’re not directly using unmanaged code, the resources will still be cleaned up but:

  • It won’t happen immediately, and your application will continue to consume those resources until the GC decides to clean them up in the background (by invoking the Finalizer — see below).

  • The GC will incur a performance penalty during the cleanup process.

If you are directly allocating unmanaged resources, then it’s critical to dispose of them yourself, since they will never be cleaned up automatically and will cause memory leaks or insufficient resources, and your systems may eventually crash.

How do we properly dispose of resources in .NET Core, you ask? To answer that, let me introduce you to IDisposable.

#aspdotnet #web-development

How to Properly Dispose of Resources In .NET Core
1.90 GEEK