Recently I'd use:
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
which registers a function like this:
private static void OnProcessExit(object? sender, EventArgs e) { //.... your code here }
and gets called properly. No .dll import. Probably a lot more multiplatform this way.