c# - Can a collection be modified by another thread during ToList() -


this question has answer here:

class sample {     private list<int> _list;     public list<int> list     {                  {              return _list.select(p => p + p).where(q => q % 2 == 0).tolist();          }     }      public void add(int n)     {         _list.add(n);     }      public void remove(int n)     {         _list.remove(n);     } } 

i have situation similar above in multithreaded environment add, remove , list accessed multiple threads simultaneously.

in cases collection modified; enumeration operation may not execute thrown in list getter, makes sense threads can add/remove while select/where operations executing.

can list modified thread during call tolist()? meaning, changing getter to

return _list.tolist().select(p => p + p).where(q => q % 2 == 0); 

be enough, or need resort locks around access _list

there's no multi-threading protection in list<t>, yes, thread could modify list during tolist call. results be:

  • everything's fine, , resulting list has new value
  • everything's fine, , resulting list doesn't have new value
  • it sets hard disk on fire (or other undefined behaviour)

basically, not safe use list<t> multiple threads without external synchronization, unless all threads reading it. either need synchronization (e.g. using synchronizedcollection<t> instead of list<t>, or handling synchronization yourself), or concurrent collection such concurrentbag<t>.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -