Skip to content
Draft
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
179 changes: 179 additions & 0 deletions controls/dev/Repeater/APITests/InspectingDataSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.CompilerServices;
using Windows.Foundation.Collections;
using Common;
using System;
using Microsoft.UI.Xaml.Controls;
using MUXControlsTestApp.Utils;
using Microsoft.UI.Private.Controls;

using WEX.TestExecution;
using WEX.TestExecution.Markup;
Expand Down Expand Up @@ -62,6 +64,183 @@ public void VerifyKeyIndexMappingNotImplementedWithoutMappingSource()
});
}

// Scenario: a subscribed ItemsSourceView's last reference is released on the finalizer thread while the UI
// thread is blocked, so its delete is queued; the UI thread then changes the source before the delete runs.
// Expected: the dying view raises nothing (raising would hand it to the handler again) and unsubscribes once
// the delete runs.
// A failure means: the handler gets a reference to a view whose queued delete then frees it.
[TestMethod]
[TestProperty("Description", "Verifies an ItemsSourceView released off the UI thread neither raises a change nor is revived while its delete is queued, and unsubscribes once deleted.")]
public void VerifyItemsSourceViewReleasedOffThreadDoesNotRaiseWhileItsDeleteIsQueued()
{
var collection = new SubscriberCountingCollection(Enumerable.Range(0, 10).Cast<object>());
object sender = null;
NotifyCollectionChangedEventHandler handler = (s, e) => sender = s;

RunOnUIThread.Execute(() =>
{
var view = CreateSubscribedView(collection, handler);
Verify.AreEqual(1, collection.Subscribers, "Precondition: the view listens to the collection.");

ReleaseOffThread(view);
collection.Add(10);
Verify.IsNull(sender, "The released view must not raise the change.");
});
IdleSynchronizer.Wait();

RunOnUIThread.Execute(() => Verify.AreEqual(0, collection.Subscribers, "The deleted view stopped listening."));
}

// Scenario: many subscribed views are released off the UI thread in each of several turns, each turn changing
// the source while their deletes are queued.
// Expected: no view raises or crashes, and every view unsubscribes once its delete runs.
// A failure means: a queued delete freed a view that was still referenced, or deleted it twice.
[TestMethod]
[TestProperty("Description", "Verifies many ItemsSourceViews released off the UI thread across turns that change their source are all deleted without raising.")]
public void VerifyManyItemsSourceViewsReleasedOffThreadAreDeleted()
{
var collection = new SubscriberCountingCollection(Enumerable.Range(0, 10).Cast<object>());
var raised = 0;
NotifyCollectionChangedEventHandler handler = (s, e) => raised++;

for (var turn = 0; turn < 20; turn++)
{
RunOnUIThread.Execute(() =>
{
var views = Enumerable.Range(0, 20).Select(_ => CreateSubscribedView(collection, handler)).ToList();
ReleaseOffThread(views.ToArray());
collection.Add(collection.Count);
collection.RemoveAt(0);
});
IdleSynchronizer.Wait();
}

RunOnUIThread.Execute(() =>
{
Verify.AreEqual(0, raised, "No released view raised a change.");
Verify.AreEqual(0, collection.Subscribers, "Every deleted view stopped listening.");
});
}

// Scenario: a view that has read its Count is released on the finalizer thread; the source changes while its delete
// is queued, and the test hook then takes a new reference to it (as resolving a XAML weak reference to it can). The
// view is then released again.
// Expected: the revived view survives its queued delete, raises a Reset and reports the count the source has now
// (the change it missed while dying), listens to the source again (raises the next change and tracks Count/GetAt),
// and is deleted once its new reference is released.
// A failure means: the queued delete freed a referenced view, the revived view kept a stale count, stayed subscribed
// through weak references that can no longer resolve (no events), or leaked.
[TestMethod]
[TestProperty("Description", "Verifies an ItemsSourceView revived while its off-thread delete is queued survives, resets to the source's current count, raises source changes again, and is deleted when released again.")]
public void VerifyItemsSourceViewRevivedWhileItsDeleteIsQueuedListensAgain()
{
if (!PlatformConfiguration.IsDebugBuildConfiguration())
{
Log.Warning("The revival test hooks exist only in Debug builds.");
return;
}

var collection = new SubscriberCountingCollection(Enumerable.Range(0, 10).Cast<object>());
ItemsSourceView revived = null;
var raised = 0;
var actions = new List<string>();
NotifyCollectionChangedEventHandler handler = (s, e) => raised++;
NotifyCollectionChangedEventHandler recorder = (s, e) => actions.Add(e.Action.ToString());

RunOnUIThread.Execute(() =>
{
ReleaseOffThread(CreateRecordedView(collection));
collection.Add(10);
revived = MUXControlsTestHooks.ReviveRecordedItemsSourceView();
Verify.IsNotNull(revived, "Precondition: the hook revived the view.");
revived.CollectionChanged += recorder;
});
IdleSynchronizer.Wait();

RunOnUIThread.Execute(() =>
{
revived.CollectionChanged -= recorder;
Verify.AreEqual("Reset", string.Join(" ", actions), "The revived view raises a Reset for the change it missed.");
Verify.AreEqual(11, revived.Count, "The revived view reports the source's current count.");
Verify.AreEqual(1, collection.Subscribers, "The revived view still listens to the collection.");
revived.CollectionChanged += handler;
collection.Add(11);
Verify.AreEqual(1, raised, "The revived view raises the change.");
Verify.AreEqual(12, revived.Count, "The revived view tracks the count.");
Verify.AreEqual(11, revived.GetAt(11), "The revived view reads the new item.");
revived.CollectionChanged -= handler;
});

RunOnUIThread.Execute(() => ReleaseOffThread(TakeWeakReference(ref revived)));
IdleSynchronizer.Wait();

// The view unsubscribes only in its destructor, so no subscriber left means it was deleted.
RunOnUIThread.Execute(() => Verify.AreEqual(0, collection.Subscribers, "Released again, the view was deleted."));

// A recorded view whose delete already ran is forgotten, not handed out.
RunOnUIThread.Execute(() => ReleaseOffThread(CreateRecordedView(collection)));
IdleSynchronizer.Wait();
RunOnUIThread.Execute(() =>
{
Verify.AreEqual(0, collection.Subscribers, "Precondition: the recorded view was deleted.");
Verify.IsNull(MUXControlsTestHooks.ReviveRecordedItemsSourceView(), "A deleted view is not revived.");
});
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference CreateRecordedView(SubscriberCountingCollection collection)
{
var view = new ItemsSourceView(collection);
Verify.AreEqual(collection.Count, view.Count, "Precondition: the view read its count.");
MUXControlsTestHooks.RecordItemsSourceViewForRevival(view);
return new WeakReference(view);
}

// Clears the only strong reference in a separate frame, so no temporary in the caller keeps the projection alive.
[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference TakeWeakReference<T>(ref T target) where T : class
{
var weak = new WeakReference(target);
target = null;
return weak;
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference CreateSubscribedView(SubscriberCountingCollection collection, NotifyCollectionChangedEventHandler handler)
{
var view = new ItemsSourceView(collection);
view.CollectionChanged += handler;
return new WeakReference(view);
}

// On the UI thread: the finalizer thread releases the views' last references (the projections are agile, so the
// release runs there rather than being marshaled back) while this thread waits for it, so each view's delete is
// queued behind the current turn.
private static void ReleaseOffThread(params WeakReference[] views)
{
for (var pass = 0; pass < 5 && views.Any(view => view.IsAlive); pass++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Verify.IsFalse(views.Any(view => view.IsAlive), "Precondition: the views' projections were collected.");
}

private sealed class SubscriberCountingCollection : ObservableCollection<object>
{
public SubscriberCountingCollection(IEnumerable<object> items) : base(items) { }

// Handlers the views added; a view removes its handler only in its destructor, so 0 means every view was
// deleted.
public int Subscribers { get; private set; }

public override event NotifyCollectionChangedEventHandler CollectionChanged
{
add { Subscribers++; base.CollectionChanged += value; }
remove { Subscribers--; base.CollectionChanged -= value; }
}
}

private static int CaptureHResult(Action action)
{
try
Expand Down
39 changes: 36 additions & 3 deletions controls/dev/Repeater/InspectingDataSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,39 @@ void InspectingDataSource::UnListenToCollectionChanges()
}
}

void InspectingDataSource::OnRevived() noexcept
{
if (!m_eventToken.value)
{
return;
}

try
{
UnListenToCollectionChanges();
m_eventToken = {};

// The tracker_refs may name a source the GC collected while the view was dying; then it stays detached. Held
// here so the source stays alive while the view subscribes.
auto const vectorView = m_vectorView.safe_get();
auto const vector = m_vector.safe_get();
if (!vectorView && !vector)
{
return;
}

// Changes the source raised while the view was dying did not reach it.
InvalidateCachedSize();
ListenToCollectionChanges();
OnItemsSourceChanged(winrt::NotifyCollectionChangedEventArgs(
winrt::NotifyCollectionChangedAction::Reset, nullptr, nullptr, -1, -1));
}
catch (...)
{
// The source refused; the view stays detached.
}
}

void InspectingDataSource::ListenToCollectionChanges()
{
if (!m_vector)
Expand All @@ -182,17 +215,17 @@ void InspectingDataSource::ListenToCollectionChanges()

if(incc)
{
m_eventToken = incc.CollectionChanged({ this, &InspectingDataSource::OnCollectionChanged });
m_eventToken = incc.CollectionChanged(WeakHandler(&InspectingDataSource::OnCollectionChanged));
m_notifyCollectionChanged.set(incc);
}
else if (const auto bindableObservableVector = m_vector.try_as<winrt::IBindableObservableVector>())
{
m_eventToken = bindableObservableVector.VectorChanged({ this, &InspectingDataSource::OnBindableVectorChanged });
m_eventToken = bindableObservableVector.VectorChanged(WeakHandler(&InspectingDataSource::OnBindableVectorChanged));
m_bindableObservableVector.set(bindableObservableVector);

}
else if(const auto observableVector = m_vector.try_as<winrt::IObservableVector<winrt::IInspectable>>()){
m_eventToken = observableVector.VectorChanged({ this, &InspectingDataSource::OnVectorChanged });
m_eventToken = observableVector.VectorChanged(WeakHandler(&InspectingDataSource::OnVectorChanged));
m_observableVector.set(observableVector);
}
}
Expand Down
21 changes: 21 additions & 0 deletions controls/dev/Repeater/InspectingDataSource.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,27 @@ class InspectingDataSource :
void UnListenToCollectionChanges();
void ListenToCollectionChanges();

// The source holds its handlers weakly, so once this view's last reference is gone it no longer raises changes,
// which would hand it out again while its delete is queued. Not the { get_weak(), &method } delegate form: that
// resolves to InspectingDataSource, which has no producer of its own (the interfaces are ItemsSourceView's). Keep
// C++/WinRT's own weak reference here; a QI-based one (make_weak, IWeakReferenceSource) is XAML's, through
// m_inner, and still resolves after final_release.
template <typename Sender, typename Args>
auto WeakHandler(void (InspectingDataSource::*method)(Sender const&, Args const&))
{
return [weakThis = ItemsSourceView::get_weak(), self = this, method](Sender const& sender, Args const& args)
{
if (auto const strongThis = weakThis.get())
{
(self->*method)(sender, args);
}
};
}

// A reference taken while the delete was queued revived the view, and the weak references the handlers hold stay
// dead, so subscribe again with a new one.
void OnRevived() noexcept override;

void OnCollectionChanged(
const winrt::IInspectable& sender,
const winrt::NotifyCollectionChangedEventArgs& e);
Expand Down
23 changes: 23 additions & 0 deletions controls/dev/Repeater/ItemsSourceView.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,29 @@

#pragma region IDataSource

#if DBG
ItemsSourceView::~ItemsSourceView()
{
auto expected = this;
s_revivalTarget.compare_exchange_strong(expected, nullptr);
}

void ItemsSourceView::RecordForRevival(winrt::ItemsSourceView const& view) noexcept
{
s_revivalTarget = view ? winrt::get_self<ItemsSourceView>(view) : nullptr;
}

winrt::ItemsSourceView ItemsSourceView::ReviveRecorded() noexcept
{
// Deletes run on the UI thread, as this test hook does, so a recorded view is not freed under it.
if (auto const view = s_revivalTarget.exchange(nullptr))
{
return *view;
}
return nullptr;
}
#endif

int32_t ItemsSourceView::Count()
{
if (m_cachedSize == -1)
Expand Down
21 changes: 21 additions & 0 deletions controls/dev/Repeater/ItemsSourceView.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

#pragma once

#include <atomic>

#include "ItemsSourceView.g.h"

class ItemsSourceView :
Expand Down Expand Up @@ -36,7 +38,26 @@ class ItemsSourceView :
virtual int IndexOfCore(winrt::IInspectable const& value);
#pragma endregion

// Called by ReferenceTracker when a reference taken while this view's delete was queued revives it.
virtual void OnRevived() noexcept {}

#if DBG
~ItemsSourceView();

// MUXControlsTestHooks (Debug builds only): records a view without a reference, so a test can release it and take a new reference while
// its queued delete has not run. Deleting the view forgets it, so a later revive returns null instead of a freed view.
static void RecordForRevival(winrt::ItemsSourceView const& view) noexcept;
static winrt::ItemsSourceView ReviveRecorded() noexcept;
#endif

protected:
void InvalidateCachedSize() noexcept { m_cachedSize = -1; }

private:
#if DBG
static inline std::atomic<ItemsSourceView*> s_revivalTarget{};
#endif

event_source<winrt::NotifyCollectionChangedEventHandler> m_collectionChangedEventSource{ this };
int m_cachedSize{ -1 };
};
Loading
Loading