Skip to content

Fix an InvalidOperationException when WeakEventTable.Purge is called …#11521

Open
kmaddock wants to merge 1 commit intodotnet:mainfrom
kmaddock:dev/kester/issue-6452-weakeventmanager
Open

Fix an InvalidOperationException when WeakEventTable.Purge is called …#11521
kmaddock wants to merge 1 commit intodotnet:mainfrom
kmaddock:dev/kester/issue-6452-weakeventmanager

Conversation

@kmaddock
Copy link

@kmaddock kmaddock commented Mar 11, 2026

…with EnableWeakEventMemoryImprovements enabled

Fixes #6452

Description

If EnableWeakEventMemoryImprovements is true, the WeakEventTable.Purge enumerates through _dataTable calling WeakEventManager.Purge on each list:

IDictionaryEnumerator ide = _dataTable.GetEnumerator() as IDictionaryEnumerator;
while (ide.MoveNext())
{
    ...
    foundDirt |= key.Manager.PurgeInternal(source, ide.Value, purgeAll);
    ...
}

WeakEventManager.PurgeInternal redirects to .Purge, which will check the ListenerList for concurrent readers, and clone and update Table (_dataTable) if concurrent readers exist:

if (ListenerList.PrepareForWriting(ref list) && source != null)
{
    Table[this, source] = list;
}

Writing to _dataTable invalidates the enumerator in WeakEventTable, which will throw an InvalidOperationException.

This PR exits WeakEventManager.Purge if EnableWeakEventMemoryImprovements is true, the list purge will be retried next time WeakEventTable is purged,

Customer Impact

Our App throws InvalidOperationException and crashes.

Regression

No

Testing

I reprod with the test case attached to issue #6452 and confirmed that this PR fixes it.

Risk

It seems pretty low risk to me

Microsoft Reviewers: Open in CodeFlow

…with EnableWeakEventMemoryImprovements enabled
@kmaddock kmaddock requested a review from a team March 11, 2026 21:51
@dotnet-policy-service dotnet-policy-service bot added PR metadata: Label to tag PRs, to facilitate with triage Community Contribution A label for all community Contributions labels Mar 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Community Contribution A label for all community Contributions PR metadata: Label to tag PRs, to facilitate with triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WeakEventManager lock issue

1 participant