As far as I understand, this is a pointer data type, i.e. it is passed in function not object, and the link? Then if I create a List object somewhere. And after that I will delete / add lines to it in several streams - it seems to me that an exception will arise since I'm trying to change the same object from different threads at the same time. Or does it work somehow differently?

  • There is a ConcurrentBag <T> for the list in the streams ....... and there is also a SynchronizedCollection <T> ......... in general, thread-safe docs.microsoft.com/en is used to work in streams -us / dotnet / standard / collections / ... - Alexey Shimansky
  • Yes sir. System.Collections.Concurrent.ConcurrentBag<T> this is a thread-safe replacement for System.Collections.Generic.List<T> .......... Also, as I wrote above, to work in streams for collections is presented whole list - Alexey Shimansky
  • @ Alexey Shimansky How is she a replacement? List keeps order, but ConcurrentBag isn’t - vitidev
  • @vitidev have suggestions better? - Alexey Shimanskyj
  • 2
    @ Alexey Shimansky is a collection of different logic. Therefore, it should not be said that one replaces the other in a multithreaded environment. - vitidev

1 answer 1

List <> is indeed a reference data type. The memory for it is allocated on the heap and the link to the address in the heap is transmitted everywhere. Therefore, to duplicate, as you write in the comments, the List itself cannot. But when working with it from multiple streams, there may indeed be an unexpected result. This is how you organize access to the collection and what you will do with it. You can also throw an exception if, for example, by indexing an element that has already been deleted by another thread. If you need a thread-safe collection, then you already have advised Concurrent collection. The alternative is to organize thread safety with your hands, for example through lock (object).