← 输入框|github.com|刷新
Skip to content

Memory not released upon multiple Initialize/Shutdown #2594

Open

Description

@Ledragon

Exectuing the following code in a basic Console app leads to the application consuming more and more memory:

            Runtime.Runtime.PythonDLL = @"C:\ProgramData\WideTech\Python\python38.dll";
            PythonEngine.PythonHome = @"C:\ProgramData\WideTech\Python\";
            var count = 1000;
            for (int i = 0; i < count; i++)
            {
                PythonEngine.Initialize();
                PythonEngine.Shutdown();
            }

I am on windows 11 (64bit), using PythonNet v3.0.5, combined with Python 3.8 (happens with Python 3.12 as well).

For more context, we have a WebAPI that runs python 3 code that interacts with C# code. I tried avoiding initalization and shutdown systematically, but then I encounter API crashes. While current implementation might not be perfect (especially given 2008 - that we are facing as well, but is not the topic), it works, besides the increasing memory consumption.

Am I missing anything regarding resources freeing?

Activity

  1. Ledragon commented on May 28, 2025

    @Ledragon
    Author

    Hey,
    Any comment on this? Not asking for a solution, but maybe just an insight on knowing if what I am doing is intrinsically wrong?

  2. kunom commented on Jul 18, 2025

    @kunom

    When run from VS Debugger against Python 3.13.3 official release, we seem to leak 25 objects/1.51 kB per iteration, mostly anonymous types within Python.Runtime.Interop:

    Image Image

    They seem to be rooted at the following static variables:

    • all new objects: Python.Runtime.Interop.allocatedThunks
    • additionally, the "+5" instances: Python.Runtime.SlotsHolder

    At least the allocatedThunks member is add-only, based on the "find all references" result:

    Image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions