Potential memory leak in CoreClr p/invoke under Windows. RRS feed

  • Question

  • Run this code as a .NET Framework (tested with 4.7.2) app and it will go forever. Perform.exe wills how a flat line for “Private Bytes” for the process.

    Run this code as a .NET Core (tested with 2.1) app and it will continuously leak memory. Perform.exe will show “Private Bytes” being used and never freed. A leak of about 16Kbytes/second.

    Any hint is appreciated.

    using System;
    using System.Runtime.InteropServices;
    namespace test
      class Program
         static void Main(string[] args)
            IntPtr userData = new IntPtr(42);
            int iter = 0;
          while (true)
               // Make p/Invoke call to anything that accept a callback, such as user32.dll EnumWindows
               EnumWindows(MyEnumProc, userData);
         private static int MyEnumProc(IntPtr hwnd, IntPtr lParam)
            int magic = lParam.ToInt32();
            if (magic != 42) throw new InvalidOperationException("Something is wrong");
            // Stop at first Window
            return 0;
       private delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
       private static extern int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

    Monday, November 25, 2019 10:29 PM

All replies

  • Hi Ike Starnes, 

    Thank you for posting here.

    According to your question, I make a test based on your code.

    The problem may be caused by the differences between .NET Framework and .NET Core, and I suggest you report a problem in developer community for more help.

    Thank you for your understanding.

    Best Regards,

    Xingyu Zhao

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, November 26, 2019 6:04 AM
  • Not sure I agree .net core is leaking memory here.   Any unmanaged resource created by a function is called with p invoke will not be garbage collected.  There are few suggestions for how to use eyebrows here


    Tuesday, November 26, 2019 10:40 AM