C# GC delegates?
How can I know when GC starts? Can I give to GC some delegates for such events like "OnStart" and "On开发者_StackOverflowEnd"?
You can't. You only have a Dispose
method on your class when you implement an IDisposable
. This is for freeing up resources. It gets called when the object "destructs". Garbage collection itself is a black box.
For more information, check: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
If you really want to to when GC happens you can create an object which has a finalizer and immeditaly set the reference to it to null. This way, the object if still generation 0 and will likely garbage collected the next time the GC runs. After the GC is done, your finalizer will probably be called, so you know that GC has happened.
Note that I doesn't recommend this and that behaviour is not guaranteed.
If you just want to know when GC runs for curiosity and educational purposes you can use a clr memory profiler tool which usually shows you when and how often GC happens and which objects get collected.
in .NET 4, you can use Garbage Collection Notifications
精彩评论