2

I was just wondering if there is an overridable callback for the garbage collector begin/end in the .NET runtime/C#. I will also state that I have no intentions of attempting to control the GC, I am just curious.

And if not, what would be the best way to replicate this behavior?

Krythic
  • 4,184
  • 5
  • 26
  • 67
  • 3
    https://msdn.microsoft.com/en-us/library/cc713687.aspx and http://stackoverflow.com/questions/3678056/is-there-an-event-for-when-garbage-collection-occurs-in-net may be of some help. – Ron Beyer May 24 '15 at 17:16

1 Answers1

6

You can't get notification directly in manged code because managed code is suspended (or at least not guaranteed to run your thread in case of background GC) during GC.

Options:

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • Managed code cannot run during compactation regardless of the GC flavor. Besides this it is a really good answer. – Alois Kraus May 24 '15 at 17:43
  • @AloisKraus It is somewhat open question if OP wanted to measure whole begin/end or just precise suspension time... I've added link to the article that talks about difference, but one would need to read way more to know what to measure... – Alexei Levenkov May 24 '15 at 18:27
  • @AlexeiLevenkov I was planning on logging frequency after specific tasks. Game cycles and what have you. – Krythic May 24 '15 at 18:31
  • @Krythic perfcounters would likely be good enough - https://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx, http://blogs.msdn.com/b/maoni/archive/2004/06/03/148029.aspx – Alexei Levenkov May 24 '15 at 18:36