.NET object is never collected once a Python event handler has been attached, even after removing it (3.2.1, regression of #1972?) · Issue #2755 · pythonnet/pythonnet
Repository navigation
.NET object is never collected once a Python event handler has been attached, even after removing it (3.2.1, regression of #1972?) #2755
New issue
New issue
Backlog
Backlog
.NET object is never collected once a Python event handler has been attached, even after removing it (3.2.1, regression of #1972?) #2755
Description
@2014jorgealvarez-debug's profile 2014jorgealvarez-debug opened on Nov 26, 2026Environment
- pythonnet 3.2.1, .NET Framework 4.8 (
load("netfx"), CLR 4.0.30319.42000) - Python 3.12.10 (64-bit), Windows 11
Description
If a Python function is attached to an event of a .NET object, that object is never garbage collected, even after the handler is removed, the object is disposed, and both the Python and .NET collectors are forced. Without the handler, the same object is collected.
The 3.0.1 changelog lists a fix for this exact case ("Fixed objects leaking when Python attached event handlers to them even if they were later removed", #1972 / #1973 ). So this looks like a regression.
Minimal reproduction
import gc
import time
from pythonnet import load
load("netfx")
import clr
clr.AddReference("System.Windows.Forms")
import System
from System.Windows.Forms import Application, Form
def handler(*_):
pass
def cycle(attach, remove):
f = Form()
if attach:
f.Shown += handler
f.Show()
Application.DoEvents()
f.Close()
Application.DoEvents()
if remove:
f.Shown -= handler
f.Dispose()
return System.WeakReference(f)
def collect():
for _ in range(6):
time.sleep(0.2)
gc.collect()
System.GC.Collect()
System.GC.WaitForPendingFinalizers()
for name, attach, remove in [
("no handler", False, False),
("handler attached, then removed", True, True),
("handler attached, not removed", True, False),
]:
refs = [cycle(attach, remove) for _ in range(5)]
collect()
print(f"{name}: {sum(r.IsAlive for r in refs)} of 5 still alive")
Output (same in every run)
no handler: 0 of 5 still alive
handler attached, then removed: 5 of 5 still alive
handler attached, not removed: 5 of 5 still alive
Expected
- In the first two cases, 0 of 5 still alive.
- Arguably in the third as well, because in .NET an object that only references its own handler is collectable.
Notes
- We see the same thing with a Python subclass of
Form(__namespace__set) that subscribes one of its own methods. - Impact: pywebview's WinForms backend (
BrowserForm) attaches Python handlers to its own events. Every window that is created and destroyed stays in memory with its WebView2 control. Measured over 200 create/destroy cycles: about +28 MB, +100 threads and +300 GDI objects per 100 windows. Part of that has other causes on the pywebview side, which we are reporting there. - We only tested the .NET Framework runtime (
netfx), which is what pywebview uses.