Memory Leak in .NET

Problem

C#을 사용할 때 메모리 누수(memory leak)로 인해 프로그램이 중지됩니다. Task ManagerPerformance 열어서 확인할 수 있습니다. 프로그램을 실행하는 동안 GPU 메모리가 얼마나 사용되는지 확인하십시오.

.NET에서 샘플을 실행할 때 메모리 누수

Possible cause

IDisposable 개체가 삭제되지 않았기 때문에 메모리 누수가 자주 발생합니다. garbage 수집기는 어플리케이션 메모리를 처리하고 메모리가 부족해지기 전에 참조되지 않은 개체를 정리합니다. 그러나 garbage 수집기는 GPU 메모리 사용량을 인식하지 못합니다. 따라서 GPU 메모리가 가득 차기 전에 제 시간에 정리되지 않을 수 있습니다.

아래 예제 코드는 3개의 획득으로 구성된 HDR 이미지를 루프에서 캡처할 때 메모리 누수를 일으킵니다.

// This code results in memory leak.

using System;
using System.Collections.Generic;

class memoryLeak
{
    static int Main()
    {
        try
        {
            var zivid = new Zivid.NET.Application();

            Console.WriteLine("Connecting to camera");
            var camera = zivid.ConnectCamera();

            Console.WriteLine("Configuring settings");
            var settings = new Zivid.NET.Settings();
            foreach (var aperture in new double[] { 9.57, 4.76, 2.59 })
            {
                Console.WriteLine("Adding acquisition with aperture = " + aperture);
                var acquisitionSettings = new Zivid.NET.Settings.Acquisition { Aperture = aperture };
                settings.Acquisitions.Add(acquisitionSettings);
            }

            while (true)
            {
                var frame = camera.Capture(settings);
                Console.WriteLine("Captured frame (HDR)");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            return 1;
        }
        return 0;
    }
}

var frame = camera.Capture(settings) 이 새로운 객체 frame 를 생성할 때 어떻게 동작하는지 확인합니다. 이 개체는 다음 프레임을 캡처할 때 삭제되지 않습니다.

Solution

이를 완화하려면 using keyword를 사용하여 결정적 메모리 정리를 강제 실행하는 것이 좋습니다.

using (var frame = camera.Capture(settings))
{
    Console.WriteLine("Captured frame (HDR)");
}

각 캡처 후에 프레임을 명시적으로 삭제할 수도 있습니다.

var frame = camera.Capture(settings);
Console.WriteLine("Captured frame (HDR)");
frame.Dispose();

task manager 에서 메모리 사용량을 확인하여 더 이상 메모리 누수가 없는지 확인할 수 있습니다.

.NET에서 샘플을 실행할 때 메모리 누수 없음