dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.27k stars 5.9k forks source link

Recommendations are confusing and conflicting #32837

Open Robin-G opened 1 year ago

Robin-G commented 1 year ago

Hello,

the article recommends using finalizers in order to release resources. However, it - rightly - contains a note, that highlights that finalizers may not be called at all (for .NET 5 or later).

Let us consider a resource which uses lock files. The resource is obtained in the constructor (the lock file is created) and released - as recommended - with a finalizer (which deletes the lock file). Since in .NET 5 and later the finalizer may not be called at the termination of the program the lock file remains and the resource is never again released. The article only suggests using IDisposable if it is necessary to release the resource fast (which isn't the case in this example).

The recommendation probably should be amended that only resources which are released automatically at the termination of the program can use the finalizer to free them. Otherwise they might never be released.


Document Details

Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.

BillWagner commented 1 year ago

hi @Robin-G

This is a bit of a special case. In this example, you should implement IDisposable to release the lock file, and handle the ProcessExit event to ensure that the Dispose method is called.

I'll add this enhancement to our backlog to update.