Can ToArray() throw an exception?

前端 未结 5 1504
不知归路
不知归路 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 13:56

    When thread-safety is not explicitly guaranteed by the docs or by principle you cannot assume it. If you do assume it you risk putting a class of bugs into production that is undebuggable and has the potential to cost you a lot of productivity/availability/money. Are you willing to take that risk?

    You can never test something to be threadsafe. You can never be sure. You cannot be sure that a future version behaves the same way.

    Do it the right way and lock.

    Btw, these remarks were for List.ToArray which is one of the more safe versions of ToArray. I understand why one would mistakenly think it can be used concurrently with writes to the list. Of course IEnumerable.ToArray cannot possibly be threadssafe because that is a property of the underlying sequence.

提交回复
热议问题