Can ToArray() throw an exception?

前端 未结 5 1528
不知归路
不知归路 2020-12-31 13:54

While the answer to this question is excellent, it implies that you should surround calls to List.ToArray() in a lock for concurrency. this blog post also implies that it c

5条回答
  •  长发绾君心
    2020-12-31 14:09

    It seems you are confusing two things:

    • List does not support being modified while it is enumerated. When enumerating a list, the enumerator checks if the list has been modified after each iteration. Calling List.ToArray before enumerating the list solves this problem, as you're enumerating a snapshot of the list then and not the list itself.

    • List is not a thread-safe collection. All of the above assumes access from the same thread. Accessing a list from two threads always requires a lock. List.ToArray is not thread-safe and doesn't help here.

提交回复
热议问题