How can I find out how many objects are created of a class

后端 未结 2 1323
醉酒成梦
醉酒成梦 2020-12-03 15:28

How can I find out how many objects are created of a class in C#?

相关标签:
2条回答
  • 2020-12-03 16:18

    Is this a class that you've designed?

    If so, add a counter to the class that is incremented in the constructor and decremented in Dispose.

    Potentially you could make this a performance counter so you can track it in Performance Monitor.

    0 讨论(0)
  • 2020-12-03 16:31

    You'd have to put a static counter in that was incremented on construction:

    public class Foo
    {
        private static long instanceCount;
    
        public Foo()
        {
            // Increment in atomic and thread-safe manner
            Interlocked.Increment(ref instanceCount);
        }
    }
    

    A couple of notes:

    • This doesn't count the number of currently in memory instances - that would involve having a finalizer to decrement the counter; I wouldn't recommend that
    • This won't include instances created via some mechanisms like serialization which may bypass a constructor
    • Obviously this only works if you can modify the class; you can't find out the number of instances of System.String created, for example - at least not without hooking into the debugging/profiling API

    Why do you want this information, out of interest?

    0 讨论(0)
提交回复
热议问题