Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ToolStrip memory leak due to MouseHoverTimer and #4808 #11358

Merged
merged 3 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4799,9 +4799,16 @@ internal void OnItemAddedInternal(ToolStripItem item)
}
}

internal void OnItemRemovedInternal(ToolStripItem item)
internal void OnItemRemovedInternal(ToolStripItem item, ToolStripItemCollection itemCollection)
{
KeyboardToolTipStateMachine.Instance.Unhook(item, ToolTip);
if (itemCollection == _toolStripItemCollection)
{
// To prevent memory leaks when item removed from main collection,
// we need to remove it from _displayedItems and _overflowItems too.
_displayedItems?.Remove(item);
JeremyKuhne marked this conversation as resolved.
Show resolved Hide resolved
_overflowItems?.Remove(item);
}
}

internal override bool AllowsChildrenToShowToolTips()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ private void OnAfterRemove(ToolStripItem item)

if (_owner is not null)
{
_owner.OnItemRemovedInternal(item);
_owner.OnItemRemovedInternal(item, this);

if (!_owner.IsDisposingItems)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ namespace System.Windows.Forms;
internal class MouseHoverTimer : IDisposable
{
private readonly Timer _mouseHoverTimer = new();

// Consider - weak reference?
private ToolStripItem? _currentItem;
private readonly WeakReference<ToolStripItem?> _currentItem = new(null);

public MouseHoverTimer()
{
Expand All @@ -18,30 +16,26 @@ public MouseHoverTimer()

public void Start(ToolStripItem? item)
{
if (item != _currentItem)
_currentItem.TryGetTarget(out var currentItem);
if (item != currentItem)
{
Cancel(_currentItem);
Cancel();
_currentItem.SetTarget(item);
}

_currentItem = item;
if (_currentItem is not null)
if (item is not null)
{
_mouseHoverTimer.Enabled = true;
}
}

public void Cancel()
{
_mouseHoverTimer.Enabled = false;
_currentItem = null;
}

/// <summary> cancels if and only if this item was the one that
/// requested the timer
/// <summary>
/// Cancels if and only if this <paramref name="item"/> was the one that requested the timer.
/// </summary>
public void Cancel(ToolStripItem? item)
{
if (item == _currentItem)
_currentItem.TryGetTarget(out var currentItem);
if (item == currentItem)
{
Cancel();
}
Expand All @@ -53,12 +47,18 @@ public void Dispose()
_mouseHoverTimer.Dispose();
}

private void Cancel()
{
_mouseHoverTimer.Enabled = false;
_currentItem.SetTarget(null);
}

private void OnTick(object? sender, EventArgs e)
{
_mouseHoverTimer.Enabled = false;
if (_currentItem is not null && !_currentItem.IsDisposed)
if (_currentItem.TryGetTarget(out var currentItem) && !currentItem.IsDisposed)
{
_currentItem.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseHover);
currentItem.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseHover);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7304,6 +7304,70 @@ public void ToolStrip_GetNextItem_ItemsBackwardExpected(ToolStripLayoutStyle too
Assert.False(toolStrip.IsHandleCreated);
}

[WinFormsFact]
public async Task ToolStrip_MouseHoverTimerStartSuccess()
{
using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
using MenuStrip menuStrip = new();
using ToolStripItem toolStripItem = menuStrip.Items.Add("toolStripItem");
toolStripItem.MouseHover += (sender, e) => cancellationTokenSource.Cancel();
((MouseHoverTimer)menuStrip.TestAccessor().Dynamic.MouseHoverTimer).Start(toolStripItem);
await Assert.ThrowsAsync<TaskCanceledException>(() => Task.Delay(SystemInformation.MouseHoverTime * 2, cancellationTokenSource.Token));
}

[WinFormsFact]
public void ToolStrip_MouseHoverTimer_ItemDispose()
{
WeakReference<ToolStripItem> currentItemWR;
using MenuStrip menuStrip = new();
MouseHoverTimer mouseHoverTimer = (MouseHoverTimer)menuStrip.TestAccessor().Dynamic.MouseHoverTimer;
TimerStartAndItemDispose();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(currentItemWR.TryGetTarget(out _));

void TimerStartAndItemDispose()
{
using ToolStripItem toolStripItem = menuStrip.Items.Add("toolStripItem");
mouseHoverTimer.Start(toolStripItem);
currentItemWR = mouseHoverTimer.TestAccessor().Dynamic._currentItem;
Assert.True(currentItemWR.TryGetTarget(out _));
}
}

[WinFormsFact]
public void ToolStrip_displayedItems_Clear()
{
using ToolStripMenuItem toolStripMenuItem = new(nameof(toolStripMenuItem));
using ToolStripMenuItem listToolStripMenuItem = new(nameof(listToolStripMenuItem));
toolStripMenuItem.DropDownItems.Add(listToolStripMenuItem);
toolStripMenuItem.DropDownOpened += (sender, e) =>
{
for (int i = 0; i < 4; i++)
listToolStripMenuItem.DropDownItems.Add("MenuItem" + i);

listToolStripMenuItem.DropDown.PerformLayout(); // needed to populate DisplayedItems collection
};

toolStripMenuItem.DropDownClosed += (sender, e) =>
{
while (listToolStripMenuItem.DropDownItems.Count > 0)
listToolStripMenuItem.DropDownItems[listToolStripMenuItem.DropDownItems.Count - 1].Dispose();

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
};

toolStripMenuItem.ShowDropDown();
Assert.Equal(4, listToolStripMenuItem.DropDown.DisplayedItems.Count);
toolStripMenuItem.HideDropDown();
Assert.Equal(0, listToolStripMenuItem.DropDown.DisplayedItems.Count);
}

[WinFormsTheory]
[InlineData(10, 10)]
[InlineData(0, 0)]
Expand Down