Memory leak when installing event handlers
See original GitHub issueEnvironment
- Pythonnet version: 2.5.2
- Python version: 3.8.3
- Operating System: Windows 10 Home (Build 19041.804)
- .NET Runtime: 4.8.04084 (I think?)
Details
- Describe what you were trying to get done.
Develop a native WinForms application.
- What commands did you run to trigger this issue?
Any WinForms app that has an event handler should exhibit the problem. Here’s a minimal example derived from the HelloApp example in the pythonnet codebase.
import clr
SWF = clr.AddReference("System.Windows.Forms")
print (SWF.Location)
import System.Windows.Forms as WinForms
from System.Drawing import Size, Point
class HelloApp(WinForms.Form):
def __init__(self):
self.ClientSize = Size(400, 200)
self.button = WinForms.Button()
self.button.Location = Point(50, 50)
self.button.Size = Size(300, 20)
self.button.Text = "Click Me!"
self.button.Click += self.button_Click
self.Controls.Add(self.button)
def button_Click(self, sender, args):
print ("Click")
def run(self):
WinForms.Application.Run(self)
def main():
form = HelloApp()
app = WinForms.Application
app.Run(form)
if __name__ == '__main__':
main()
Run the app, then really mash the “click me” button (lots - like, dozens of times). Every time you click, the app’s memory allocation increases a little bit; I’ve never seen this allocation be freed by a garbage collection cycle, even if you add a gc.collect()
call.
This problem was observed in practice with code that integrates the Python Windows Proactor with the Winforms event loop. In that code, we’re creating and scheduling a System.Action()
every 5ms to schedule an iteration of the asyncio event loop - and every time it does, there’s a small leak. Invoke that 200 times a second, and the leak adds up quickly. However, even simple button presses cause a leak.
- If there was a crash, please include the traceback here.
No crash - the app works fine; it just (slowly) leaks memory.
Issue Analytics
- State:
- Created 2 years ago
- Comments:13 (5 by maintainers)
Top GitHub Comments
I’ll add that if this is a situation where money will accelerate progress, I may be in a position to help out.
@filmor I’ve just tested the current master (23527d11) - I’m not seeing any change in behavior.