How to safely iterate though a list that may be updated on another thread? #4442
Unanswered
benstevens48
asked this question in
Q&A
Replies: 1 comment 5 replies
-
Maybe exit the loop via a cancelation token-like mechanism if the event is raised during enumeration. I don't know how reliable the timing of the event is though. |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Many of the WinRT APIs return an IVector or even IVectorView, which are projected as IList and IReadOnlyList in C#. Some of these are subject to being updated on background threads (even the read-only list), for example MediaPlaybackItem.TimedMetadataTracks. How is one meant to safely iterate through such a collection? For example, I just tried iterating though MediaPlaybackItem.TimedMetadataTracks using a foreach loop in C# and got a collection modified exception (and I am not modifying it in the loop). I guess I can do ToList first or something, but presumably that would just reduce the chance of such an exception by reducing the time spent iterating, not remove it completely (unless it uses some other internal method to get the elements from the Vector).
Is the only solution to wrap the loop in a try-catch block? In this case it would be good if the docs called out all instances where this is necessary.
Beta Was this translation helpful? Give feedback.
All reactions