Finalizers and the nasty stuff plug-ins can do if they want to...
One of the worst things I've ever found is a finalizer that does an endless loop. This will seriously take your entire system down until you kill the process running the high priority GC thread. I've found that you can get around the finalizer by calling GC.SuppressFinalize and passing in the object instance where you don't want your finalizer run. Basically what I'm after now is:
Is this a true guarantee that the finalizer won't be run?
They require high security permissions to re-register. If I lock them down to Execute permissions only can I be guaranteed they can't re-register?
Running arbitrary code is dangerous and I'd love to be able to lock things down to make it completely safe. Given access to IL level hacks people can do some nasty stuff (the various types of stack overflows that render managed threads unable to be aborted for instance).
Anyway, to check out the GC finalizer issue, simply compile the code below. If you comment out the SuppressFinalize call you'll see the impact on your system. I was playing some MP3 files in Media Player and thought for a second they had been recorded with a skip because my system was being starved for CPU time due to the GC thread hanging.
using System;
public class ClassWithFinalizer {
private string name;
public ClassWithFinalizer(string name) {
this.name = name;
}
~ClassWithFinalizer() {
Console.WriteLine(name);
while(true) { }
}
}
public class Runner {
private static void Main(string[] args) {
ClassWithFinalizer[] classes = new ClassWithFinalizer[10];
for(int i = 0; i < classes.Length; i++) {
classes[i] = new ClassWithFinalizer(i.ToString());
GC.SuppressFinalize(classes[i]);
classes[i] = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
}