简体   繁体   English

C#Collection在lambda.where上被修改了异常

[英]C# Collection was modified exception on lambda.where

I have the following code: 我有以下代码:

var actionsToExecute = _messagesToExecute.Where(m => m.CanExecute).ToList();

It runs fine 99% of the time, but every once in a while it will crash with the exception: 它在99%的时间内运行良好,但每隔一段时间就会崩溃,但异常:

Collection was modified; enumeration operation may not execute

I am a bit lost as it seems a bit random. 我有点失落,因为它似乎有点随机。 This is the first line in the method. 这是该方法的第一行。 What might cause a lambda expression to throw this exception? 什么可能导致lambda表达式抛出此异常?

It has to do with threading. 它与线程有关。 It seems like this is website code. 看来这是网站代码。 If that private variable is modified by another person visiting the site while the .ToList() is executing that exception will occur. 如果在执行.ToList()的同时访问该站点的另一个人修改了该私有变量,则该异常将发生。

The solution is to use a threadsafe collection but this isn't optimal since if many people are reading/writing to it they can only do it more or less one at a time. 解决方案是使用线程安全集合,但这不是最佳的,因为如果许多人正在阅读/写入它们,他们一次只能或多或少地执行一次。

I had a similar problem but the enumeration was not critical, it was okay to have skips or duplicates so I implemented my own enumerator that does not check to see if it was modified. 我有一个类似的问题,但枚举并不重要,可以跳过或重复,所以我实现了自己的枚举器,不检查它是否被修改。

You either need to use lock() around all your references to _messagesToExecute, or you could use something from System.Collections.Concurrent which handle locking the collection internally. 您需要在所有对_messagesToExecute的引用周围使用lock(),或者您可以使用System.Collections.Concurrent中的内容来处理内部锁定集合。

eg 例如

_messagesToExecute = new ConcurrentBag<TMessage>();

or if you'd rather use locking: 或者如果您更愿意使用锁定:

static readonly object m_lock = new object();

then whenever you update the list: 然后每当你更新列表时:

lock(m_lock){
  _messagesToExecute.Add(item);
}

and then when you're pulling out the list: 当你拿出清单时:

lock(m_lock){
    var actionsToExecute = _messagesToExecute.Where(m => m.CanExecute).ToList();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM