While scanning GC class members in IntelliSense with VS 2010 I noticed a few that looked unfamiliar. Turns out new feature allows receiving full GC notifications using the following methods:
This is how MSDN explains the main user scenario for these notifications:
There are situations in which a full garbage collection by the common language runtime may adversely affect performance. This can be an issue particularly with servers that process large volumes of requests; in this case, a long garbage collection can cause a request time-out. To prevent a full collection from occurring during a critical period, you can be notified that a full garbage collection is approaching and then take action to redirect the workload to another server instance. You can also induce a collection yourself, provided that the current server instance does not need to process requests.
I decided to try them out and wrote a test WPF app that displays a message when full GC is about to start and then another message when full GC is complete. MSDN provides a decent sample that explains the usage pattern, but in a nutshell it is:
private void GCNotifyProc() { while (true) { var gcApproachStatus = GC.WaitForFullGCApproach(-1); //wait indefinitely if (gcApproachStatus == GCNotificationStatus.Succeeded) //notify the main thread that full GC is imminent Dispatcher.Invoke(new Action(() => NotifyGCStart())); else // Main thread must have called GC.CancelFullGCNotification(..), // or notification failed, exit the procedure return;
var gcCompleteStatus = GC.WaitForFullGCComplete(-1); //wait indefinitely if (gcCompleteStatus == GCNotificationStatus.Succeeded) //notify the main thread that full GC has completed Dispatcher.Invoke(new Action(() => NotifyGCComplete())); else // Main thread must have called GC.CancelFullGCNotification(..), // or notification failed, exit the procedure return; } }
While this seems quite straightforward, I'd like to point out a few details that I learnt or realized while playing with GC notifications.
My post was just scratching the surface, but if you're looking for more in-depth info on GC notifications, I'd recommend the following blog: http://blogs.msdn.com/maoni/archive/2008/11/19/so-what-s-new-in-the-clr-4-0-gc.aspx