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: RoutedCommand CanExecuteChanged Memory Leak #66

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Labs.Catalog.Views;
using Avalonia.Labs.Input;
using Avalonia.Platform.Storage;

namespace Avalonia.Labs.Catalog.ViewModels;
Expand Down Expand Up @@ -42,6 +43,7 @@ public async void Open(object? parameter)
item.Text = file.Name;
}
}
CommandManager.InvalidateRequerySuggested();
}
}

Expand All @@ -53,6 +55,7 @@ public async void Save(object? parameter)
if (parameter is RouteCommandItemViewModel { HasChanges: true } item)
{
item.Accept();
CommandManager.InvalidateRequerySuggested();
}
await Task.CompletedTask;
}
Expand All @@ -66,6 +69,7 @@ public void Delete(object? parameter)
{
Dettails.Remove(item);
item.Accept();
CommandManager.InvalidateRequerySuggested();
}
}

Expand Down
19 changes: 13 additions & 6 deletions src/Avalonia.Labs.CommandManager/RoutedCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ namespace Avalonia.Labs.Input;
/// </summary>
public class RoutedCommand : ICommand
{
private EventHandler? _canExecuteChanged;
/// <summary>
/// The weak collection of delegates for <see cref="ICommand.CanExecuteChanged"/>.
/// </summary>
private readonly WeakCollection<EventHandler> _canExecuteChanged = new();

private RoutedCommandRequeryHandler? _handler;
private IList<KeyGesture>? _gestures;

Expand Down Expand Up @@ -63,8 +67,7 @@ public RoutedCommand(string name, KeyGesture gesture)
{
add
{
_canExecuteChanged += value;

_canExecuteChanged.Add(value!);
if (_handler is null)
{
_handler ??= new RoutedCommandRequeryHandler(this);
Expand All @@ -73,8 +76,7 @@ public RoutedCommand(string name, KeyGesture gesture)
}
remove
{
_canExecuteChanged -= value;

_canExecuteChanged.Remove(value!);
if (_handler is not null && _canExecuteChanged is null)
{
CommandManager.PrivateRequerySuggestedEvent.Unsubscribe(CommandManager.Current, _handler);
Expand Down Expand Up @@ -155,6 +157,11 @@ internal bool ExecuteCore(object? parameter, IInputElement? target)

private class RoutedCommandRequeryHandler(RoutedCommand command) : IWeakEventSubscriber<EventArgs>
{
public void OnEvent(object? sender, WeakEvent ev, EventArgs e) => command._canExecuteChanged?.Invoke(sender, e);
public void OnEvent(object? sender, WeakEvent ev, EventArgs e)
{
var list = command._canExecuteChanged.GetLiveItems();
foreach (var canExecuteChanged in list)
canExecuteChanged(sender, EventArgs.Empty);
}
}
}
79 changes: 79 additions & 0 deletions src/Avalonia.Labs.CommandManager/Utilities/WeakCollection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Based on: https://github.com/StephenCleary/Mvvm.Core/blob/cbac65eda98760cc0dabd0b82a6468be0e1dd44f/src/Nito.Mvvm.Core/WeakCollection.cs
using System;
using System.Collections.Generic;

namespace Avalonia.Utilities;

/// <summary>
/// A collection of weak references to objects.
/// </summary>
/// <typeparam name="T">The type of object to hold weak references to.</typeparam>
internal sealed class WeakCollection<T> where T : class
{
/// <summary>
/// The actual collection of strongly-typed weak references.
/// </summary>
private readonly List<WeakReference<T>> _list = [];

/// <summary>
/// Gets a list of live objects from this collection, causing a purge.
/// </summary>
/// <returns></returns>
public IReadOnlyList<T> GetLiveItems()
{
var ret = new List<T>(_list.Count);

// This implementation uses logic similar to List<T>.RemoveAll, which always has O(n) time.
// Some other implementations seen in the wild have O(n*m) time, where m is the number of dead entries.
// As m approaches n (e.g., mass object extinctions), their running time approaches O(n^2).
int writeIndex = 0;
for (int readIndex = 0; readIndex != _list.Count; ++readIndex)
{
WeakReference<T> weakReference = _list[readIndex];
T? item;
if (weakReference.TryGetTarget(out item))
{
ret.Add(item);

if (readIndex != writeIndex)
_list[writeIndex] = _list[readIndex];

++writeIndex;
}
}

_list.RemoveRange(writeIndex, _list.Count - writeIndex);

return ret;
}

/// <summary>
/// Adds a weak reference to an object to the collection. Does not cause a purge.
/// </summary>
/// <param name="item">The object to add a weak reference to.</param>
public void Add(T item)
{
_list.Add(new WeakReference<T>(item));
}

/// <summary>
/// Removes a weak reference to an object from the collection. Does not cause a purge.
/// </summary>
/// <param name="item">The object to remove a weak reference to.</param>
/// <returns>True if the object was found and removed; false if the object was not found.</returns>
public bool Remove(T item)
{
for (int i = 0; i != _list.Count; ++i)
{
var weakReference = _list[i];
T? entry;
if (weakReference.TryGetTarget(out entry) && entry == item)
{
_list.RemoveAt(i);
return true;
}
}

return false;
}
}