Threadsafe foreach enumeration of lists

后端 未结 11 1597

I need to enumerate though generic IList<> of objects. The contents of the list may change, as in being added or removed by other threads, and this will kill my enumerati

11条回答
  •  甜味超标
    2020-12-17 19:15

    So the requirements are: you need to enumerate through an IList<> without making a copy while simultaniously adding and removing elements.

    Could you clarify a few things? Are insertions and deletions happening only at the beginning or end of the list? If modifications can occur at any point in the list, how should the enumeration behave when elements are removed or added near or on the location of the enumeration's current element?

    This is certainly doable by creating a custom IEnumerable object with perhaps an integer index, but only if you can control all access to your IList<> object (for locking and maintaining the state of your enumeration). But multithreaded programming is a tricky business under the best of circumstances, and this is a complex probablem.

提交回复
热议问题