How to calculate the number of instances created between two breakpoints

I would like to do something like:

ObjectRecorder.Start();
//Do stuff here ...
ObjectRecorder.Stop();

//And get the result
List<Object> result = ObjectRecorder.GetAll();
//or even 
ObjectRecorder.GetNumberInstanceCreated();

What I'm trying to achieve

I use BlockingCollectionand profile my application, I saw TryTake create an internaly object. Since I often call this method, I would like to show the error with the unit test, and then implement a new one ImprovedBlockingQueueand see that the problem is resolved.

Any ideas?

+4
source share
2 answers

, , . , , unit test, , GC.GetTotalMemory . unit test .

, Microsoft.Diagnostics.Runtime a > ( ). :

public static void GetStats(ClrRuntime runtime)
{
    ClrHeap heap = runtime.GetHeap();
    var stats = heap.EnumerateObjects()
                    .Select(obj => new 
                    {
                        Type = heap.GetObjectType(obj),
                        ObjectAddress = obj
                    })
                    .GroupBy(g => g.Type,
                             g => g.Type.GetSize(g.ObjectAddress))
                    .Select(gr => new
                    {
                        Name = gr.Key.Name,
                        Count = gr.Count(),
                        Size = gr.Sum(x => (int)x)
                    })
                    .Where(t => !t.Name.StartsWith("System.") &&
                                !t.Name.StartsWith("Microsoft.") &&
                                !t.Name.Equals("Free"))
                    .ToList();
    Console.WriteLine("---------- Start ----------");
    foreach (var item in stats)
        Console.WriteLine("{0} {} {2}", item.Size, item.Count, item.Name);
}

:

var process = Process.GetCurrentProcess();
using (var dataTarget = DataTarget.AttachToProcess(process.Id, 1000, AttachFlag.Passive))
{
    string dacLocation = dataTarget.ClrVersions[0].TryGetDacLocation();
    ClrRuntime runtime = dataTarget.CreateRuntime(dacLocation);
    GetStats(runtime);

    List<User> list = new List<User>();
    Enumerable.Range(1, 1000).ToList().ForEach(i => list.Add(new User() { Age = i }));

    Thread.Sleep(10000);

    GetStats(runtime);
}

: AttachFlag.Passive, :

"" , . , (, GC callstacks) **, .

, .

+3

:

class ObjectRecorder
{
    static List<ObjectRecorder> valuse=new List<ObjectRecorder>();

    bool record = false;

    public ObjectRecorder()
    {
        //your code
        if (record){ valuse.Add(this); }
    }

    public void StartRecording(){ record = true; }

    public void StopRecording(){ record = false; }

    public void ResetRecording()
    {
        valuse = new List<ObjectRecorder>();
    }

    public List<ObjectRecorder> GetAll()
    {
        return valuse;
    }
}
0

All Articles