Skip to content

Memory leak when throwing exceptions in .NET and catching in Python #1476

@Rookfighter

Description

@Rookfighter

Environment

  • Pythonnet version: 2.5.2
  • Python version: issue verified on 3.7.2, 3.7.7 and 3.8.6
  • Operating System: Windows 10 64bit
  • .NET Runtime: .NET Framework 4.7.2

Details

Hello everybody and thanks for this great piece of Software!

The basic issue is:

  • if I throw a .NET exception from within C# code
  • and the exception moves into the python space
    • i.e. the C# method was called from python
  • then the memory of the exception does not get released anymore

This becomes apparent when you throw quite a lot of exceptions and your applications runs 24/7.

Reproducability

The issue is fairly easy to reproduce. I have also setup a sample repository, which reproduces the issue.

https://github.com/Rookfighter/pythonnet-memleak-exceptions

The basis instruction are:

  • setup a Visual Studio Project of the type "Class Library .NET Framework 4.7.2"
  • create a ExceptionThrower class
using System;

namespace LeakingExceptions
{
    public class ExceptionThrower
    {
        public void ThrowException()
        {
            throw new Exception("a simple exception");
        }
    }
}
  • create a python script which imports the assembly
  • create a ExceptionThrower object and call ThrowException within a looped try except block
import os
import __main__

import clr

# bin dir must be adjusted to your relative path!
bin_dir = os.path.abspath(os.path.join(os.path.dirname(__main__.__file__), '../Source/LeakingExceptions/bin/Debug'))
clr.AddReference(os.path.join(bin_dir, 'LeakingExceptions'))

from LeakingExceptions import ExceptionThrower

thrower = ExceptionThrower()

while True:
    try:
        thrower.ThrowException()
    except:
        pass
  • in the task manager you can then watch the application to accumulate memory and never release it

memleak_taskmgr

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    pFad - Phonifier reborn

    Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

    Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


    Alternative Proxies:

    Alternative Proxy

    pFad Proxy

    pFad v3 Proxy

    pFad v4 Proxy