Threadsafe foreach enumeration of lists

后端 未结 11 1615

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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 19:11

    Your problem is that an enumeration does not allow the IList to change. This means you have to avoid this while going through the list.

    A few possibilities come to mind:

    • Clone the list. Now each enumerator has its own copy to work on.
    • Serialize the access to the list. Use a lock to make sure no other thread can modify it while it is being enumerated.

    Alternatively, you could write your own implementation of IList and IEnumerator that allows the kind of parallel access you need. However, I'm afraid this won't be simple.

提交回复
热议问题