One of my WPF element is data-bound to a property that calls Count(Func) on a IEnumerable. The property displays something like the count of active entities in the system (thus the need of a Func parameter).
public int ActiveEntitiesCount
{
get
{
return Entities.Count((item) =>
{
//my own code, just a couple of value comparisons, very quick
});
}
}
.
However the IEnumerable is a list that can be changed by another thread at any time. Sometimes, the application crashes, apparently because the IEnumerable is modified while the Count function enumeration is in progress.
I can put a try-catch block, but how to get the value to be returned by that property?
Note: Using lock may be not practical, because I don’t know all the codes that’s accessing the IEnumerable
You can alleviate the issue by making a snapshot of your list before running
Counton it. Like:To truly fix the issue, you would either make it thread-safe, using any of synchronization technique or to redesign it to avoid contention.
[EDIT] Possible solution: