0

I have the following code which is called every 3 seconds continuously from a thread

public class SomeClass
{
    List<Person> _list;

    public SetList(List<Preson> list)
    {
     _list = list;
    }
    private void WorkToBeDoneEverythreeSeconds()
    {

      var filteredList= _list.Where(x= x.IsConditionValid());
    //................Use the filtered list here.........
    }
}

_list is a reference to a C# List owned by another class passed into this class. The list is updated from a different thread in its owner class. Sometimes updates happening while the Where clause is executed and Invalid operation is thrown.

What is the most efficient way to get a snapshot on the actual list when using the enumerator? I can think of creating another collection from the current collection, but doing this every 3 seconds might not be the best idea?

Jimmy
  • 3,224
  • 5
  • 29
  • 47
  • Copying the collection is alright unless GC troubles you. – Leisen Chang Jul 23 '19 at 08:54
  • There are thread safe collections: https://stackoverflow.com/questions/5874317/thread-safe-listt-property – Steve Jul 23 '19 at 08:55
  • If I change the List to a thread safe collection in the Owner class, it will slow done its operations – Jimmy Jul 23 '19 at 08:57
  • Why don't you surround the 'critical' section of your code using `lock`, so only one operation can be performed (either add or the where filter) – Thangadurai Jul 23 '19 at 08:58
  • Even if the invalid operation is thrown, you'll do the same job 3 seconds later, so I think the exception is negligible, add try-catch around it is most efficient. – shingo Jul 23 '19 at 09:04
  • Catching the exception and ignoring for the process to catch up after 3 seconds is not an option – Jimmy Jul 23 '19 at 09:12
  • Do you really need to copy the list or do you need to avoid collisions between threads? Perhaps you shpuld restate your question. – JotaBe Jul 23 '19 at 09:12
  • My need is to enumerate the list without being affected by any changes in the list in between – Jimmy Jul 23 '19 at 15:55

0 Answers0