Memory Leak in WPF CustomContextMenu Derived from ContextMenu Due to ContextMenuAutomationPeer
- Dominant language
- C#
- Stars
- 7.7k
- Forks
- 1.3k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 61
Description
### Description
In a WPF application, a memory leak occurs when using a custom ContextMenu derived class (CustomContextMenu). Even after explicitly clearing the context menu and unsubscribing from events, the CustomContextMenu instance is not garbage collected. Memory profiling indicates that the leak is caused by ContextMenuAutomationPeer.

### Reproduction Steps
1.Run the attached sample
2.Right-click on the button to display the CustomContextMenu.
3.Close the context menu by clicking outside the menu area.
4.Use a memory profiler (e.g., JetBrains dotMemory).
5.Take memory snapshots before and after opening/closing the context menu.
6.Observe that the CustomContextMenu instance is still retained in memory, even though:
- The Closed event is unsubscribed.
- The context menu is cleared and dereferenced.
[MemoryLeak-ContextMenuAutomationPeer.zip](https://github.com/user-attachments/files/21013128/MemoryLeak-ContextMenuAutomationPeer.zip)
### Expected behavior
The CustomContextMenu instance should be garbage collected after being cleared and dereferenced.
### Actual behavior
The CustomContextMenu instance remains in memory due to a reference held by ContextMenuAutomationPeer, causing a memory leak.
### Regression?
_No response_
### Known Workarounds
_No response_
### Impact
Due to the memory leak in CustomContextMenu, its owning window and associated UI elements may also remain in memory, leading to increased memory usage.
### Configuration
_No response_
### Other information
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.