8000 Memory leak when throwing exceptions in .NET and catching in Python · Issue #1476 · pythonnet/pythonnet · GitHub
[go: up one dir, main page]

Skip to content
Memory leak when throwing exceptions in .NET and catching in Python #1476
Closed
@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

    0