且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么没有在某些情况下foreach循环的工作?

更新时间:2021-10-09 17:45:40

您的问题是,名单,LT的构造; T> 创建从的IEnumerable (这是你叫什么),一个新的列表不是线程安全的相对于它的参数。什么情况是,尽管这样的:

Your problem is that the constructor of List<T> that creates a new list from IEnumerable (which is what you call) isn't thread-safe with respect to its argument. What happens is that while this:

 new List<string>(Foo.Requests)

执行时,另一个线程修改 Foo.Requests 。你必须将其锁定为通话时长。

is executing, another thread changes Foo.Requests. You'll have to lock it for the duration of that call.

随着指出由Eric,另一个问题列表&LT; T&GT; 不能保证安全,为读者而另一个线程正在改变它读,无论是。即并发读取器是好的,但并发读写器都没有。而当你锁定你写反对对方,你也别把你读对你写。

As pointed out by Eric, another problem List<T> isn't guaranteed safe for readers to read while another thread is changing it, either. I.e. concurrent readers are okay, but concurrent reader and writer are not. And while you lock your writes against each other, you don't lock your reads against your writes.