c# - Change List externally while being iterated -


i have following code:

    private static list<string> mylist;      static void main()     {         mylist = new list<string>();          var websocketclient = new websocket("wss://ws.mysite.com");         websocketclient.messagereceived += iteratemylist;          var updatelisttimer = new timer();         updatelisttimer.elapsed += updatemylist;          console.readline();     }      public static void iteratemylist(object sender, eventargs e)     {         foreach (var item in mylist)         {             //do item         }     }      public static void updatemylist(object sender, eventargs e)     {         // add new items , remove items mylist.      } 

what happens when timer tick , new websocket message events collide?

iteratemylist() iterating mylist , updatemylist() updating @ same time.

will exception?

when attempt insert during iteration, raise exception , error saying attempting "read or write protected memory".

to solve this, use concurrentbag<t> or other concurrent collecton. these collection objects threadsafe. if not care order, recommend using concurrentbag performance reasons.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -