Is it possible to determine when the Garbage collection runs?

I am analyzing my code(in a GUI app) to determine in which step the delay is occuring. To do so, I am printing out the time stamp in "ss.fff" format to print the milliseconds. What i found is that there is more than 100 ms delay occuring in the 10 steps of the code. The delay is not occuring at the same point all the time. Sometimes the delay occurs between steps 2 and 3, sometime between 6 &7 and sometimes in between 9 & 10. Also the delay is not always constant and varies from 100 to 400 ms. The entire code is in a single method and is accessing objects existing in the current thread. I m suspecting that the garbage collection might be running in between. Is it possible to figure out when the garbage collection occurs in C#?
Who is Participating?
Garbage collector runs only when application consumes almost all available memory, this doesn't happen every second. To make presize time management for functions you can use Stopwatch class (VS 2005).
Notice that Windows is not real time system, it can always make thread context switch, this makes execution time unpredictable. You always need to count average time, don't beleive to single result.
If you explicity want to know when the GC runs then use the .NET CLR profiler and the .NET performance counters in your system tools.  They tell you EXACTLY what is getting gc'ed, whate generation ect.  The performance counters allow you to profile ANYTHING including odd things like when finally blocks are called.

From your post above I can assure you that the GC is NOT causing that delay.  What is the code doing exactly?
class DetectGC
    ~DetectGC() {
        MessageBox.Show("Garbage collected."); // Runs on finalization thread!

// Usage
DetectGC gdc = new DetectGC();
gdc = null;
yes but doesnt scale.  you'll find much more valuble info in the CLR profiler and perfmons.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.