TrackingCollection.CollectionChanged fired too early when removing items
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 7.8k
- Forks
- 1.2k
- Avg merge
- 2d 17h
- Merged PRs (30d)
- 49
Description
Release Type: Official Release
Version: 4.3.0.2507 and prior
Platform(s): All
Describe the bug
TrackingCollection.Remove/RemoveAt fires the CollectionChanged event before it changes the collection.
This means it is not safe to query the collection in the event handler.
To Reproduce
Steps to reproduce the behavior:
Rough code:
var coll = new TrackingCollection<int>();
coll.Add(1);
coll.CollectionChanged += (sender, e) => { Debug.Assert(coll.Count == 0); };
coll.RemoveAt(0); // Will fail the assert
Expected behavior
Item should already be removed when the event is fired.
Workaround
Delay any code that requires iterating or calling the collection directly when the event fires.
Related discussion
- Not sure if
TrackingCollectionis meant to be used by external users. Having aCollectionChangingwould ensure the correct event is fired for the correct timing (assuming you want to see the changing event instead of always changed event). - The set item method triggers 2 events
NotifyCollectionChangedAction.Remove->NotifyCollectionChangedAction.Add, instead of a singularNotifyCollectionChangedAction.Replacewhich is a bit clunky but would be considered another breaking change to fix. FastTrackingCollectionhas the same issue.TrackingDictionaryhas the same issue.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the TrackingCollection.Remove and RemoveAt implementations and the related FastTrackingCollection and TrackingDictionary code mentioned in the report. Reproduce the event-handler scenario, then inspect the existing collection tests or add coverage for querying the collection during removal. Done means CollectionChanged is raised after removal while preserving the intended event behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100