I have an ObservableCollection of Logs that I have bound to my GUI through a property
public ObservableCollection<ILog> Logs {get; private set;}
There is a requirement to show a subset of the logs somewhere else so I have:
public ObservableCollection<ILog> LogsForDisplay
{
get
{
ObservableCollection<ILog> displayLogs = new ObservableCollection<ILog>();
foreach (Log log in Logs.ToList()) // notice the ToList()
{
if (log.Date != DateTime.Now.Day)
continue;
displayLogs.Add(log);
}
return displayLogs;
}
Before I added the "ToList()" I got exceptions occasionally about "Collection was modified; enumeration operation may not execute" Makes sense - somebody could add to Logs while I'm iterating over it. I got the idea of "ToList" from Collection was modified; enumeration operation may not execute which seems to suggest that ToList is the way to go and implies it's thread safe. But is ToList() thread safe? I assume that internally it must use the list and iterate over it? And what if someone adds to that list at the same time? Just because I haven't seen a problem doesn't mean there isn't one.
My question. Is ToList() thread safe and if not, what is the best pattern for protecting Logs? If ToList() is thread safe, do you have a reference?
Bonus question. If the requirements were to change and all I needed to display on the GUI was LogsForDisplay and NOT Logs, could I change Logs to something else that would solve the problem? Such as ImmutableList ? Then I wouldn't have to call ToList<> which I assume takes some time to make a copy.
Let me know if I can provide clarification. Thanks,
Dave