Can I get instances of live objects of a certain type in C #?

This is a C # 3.0 question. Can I use the reflection or memory management classes provided by the .net framework to count all live instances of a particular type in memory?

I can do the same using the memory profiler, but it takes extra time to reset the memory and use third-party software. I only want to control a certain type, and I want an easy method that can easily be used for unit tests. The goal of counting live instances is to ensure that I do not have the expected live instances that cause a memory leak.

Thanks.

+3
source share
2 answers

To do this entirely inside the application, you can make an instance counter, but it must be explicitly encoded and managed within each class - there is no silver bullet that I know of, to allow you to request a framework from within the executable code to find out how many copies alive.

What you are asking is really a profiler domain. You can purchase it or create it yourself, but it requires your application to run as a child of the profiler. By the way, riding on your own is not an easy task.

If you want to consider the instance counter, it should be something like this:

public class MyClass : IDisposable
    public MyClass()
    {
        ++ClassInstances;
    }

    public void Dispose()
    {
        --ClassInstances;
    }

    private static new object _ClassInstancesLock;
    private static int _ClassInstances;
    private static int ClassInstances
    {
        get
        {
            lock (_ClassInstancesLock)
            {
                return _ClassInstances
            }
        }
    }

, ; 0% ( ), Dispose, , GC. , , , - , , windbg.

: , , , , . , IMO, ANTS Memory Profiler. 5 - , SKU ( ), Memory Profiler 5.0 . , , -.

0 , , ANTS, . .

+1

, , - - CLR Profiling API . , API- , , , , CLR ( API- ).

VB.NET , , ( ). , , , PostSharp .

0

Source: https://habr.com/ru/post/1712528/


All Articles