Visual Studio 2022 analyzes C# program memory leaks

background

Recently, our project has experienced a memory surge. When we first discussed it, we found that after communicating with the robot, the memory would slowly increase until the system crashed.

example

Since I am just introducing a simple solution, I will write a relatively simple example to demonstrate it. The code is as follows:

internal class Program
{
    static void Main(string[] args)
    {
        Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
        for(int i = 0; i < 100000000; i++)
        {
            dict[i]=new List<int>();
            for(int j = 0; j < 100000000; j++)
            {
                dict[i].Add(j);
            }
            Console.WriteLine($"dict[{i}].Count={dict[i].Count}");
        }
        Console.WriteLine($"dict.Count={dict.Count}");
    }
}

It is not difficult to see that this is an example of a memory leak deliberately written, in which a dictionary dict is created, the keys are integers, and the values ​​are also integers. If objects are continuously created and put into the dictionary, the memory will continue to grow and eventually crash.

debug

1. Open vs2022 and change the project startup mode to Release

2. Select "Debug->Performance Probe"

3. Check the memory usage item and then start detection

4. During the detection process, we can take multiple snapshots of the occupancy of each object in the current memory.

5. When you have almost captured the photos, you can stop collecting and start analyzing.

 

 6. As above, we select the last snapshot result and click to view the stack

7. There are a lot of things. If you can’t understand it, it doesn’t matter. Choose to display dead objects, because many cases of memory leaks are caused by dead objects not being released.

8. There are still too many, but it can be seen that it is an Int32 array problem. We can continue to filter other ones and select large objects in the code.

9. Click on the finally locked Int32[] and you will see its calling status.

10. The bottom layer of List in C# is maintained by an array. Click List<int> to continue expanding.

As you can see, the problem with the dictionary has been pinpointed. Because we wrote the code, we know exactly where the dictionary is called, so we have the direction to investigate.​ 

Guess you like

Origin blog.csdn.net/qq_36694133/article/details/134703315