List concurrent removing and adding

前端 未结 5 1125
渐次进展
渐次进展 2020-12-17 16:36

I am not too sure, so i thought i\'d ask. Would removing and adding items to a System.Collections.Generic.List<> object be non-thread safe?

My sit

相关标签:
5条回答
  • 2020-12-17 17:05

    Actually, sometimes List<> is thread-safe, and sometimes not, according to Microsoft:

    Public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

    but that page goes on to say:

    Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

    0 讨论(0)
  • 2020-12-17 17:12

    Yes, adding and removing items from a List<> is not thread safe, so you need to synchronise the access, for example using lock.

    Mind that the lock keyword in no ways locks the object that you use as identifier, it only prevents two threads to enter the same code block at the same time. You will need locks around all code that accesses the list, using the same object as identifier.

    0 讨论(0)
  • 2020-12-17 17:14

    At the time of the question there wasn't .NET Framework 4 yet, but the people who are faced the problem now should try to use collections from System.Collections.Concurrent namespace for dealing with thread-safe issues

    0 讨论(0)
  • 2020-12-17 17:16

    List<T> is not thread-safe, so yes, you will need to control access to the list with a lock. If you have multiple threads accessing the List make sure you have them all respect the lock or you will have issues. The best way to do this would to be to subclass the List so that the locking happens automatically, else you will more than likely end up forgetting eventually.

    0 讨论(0)
  • 2020-12-17 17:16

    Definitely using lock for particular code makes it thread safe, but I do not agree with it for current scenario.

    You can implement method Synchronized to make collection thread safe. This link explains why and how to do that.

    Another purely programmatic approach is mentioned in this link, though I never tested it firsthand but it should work.

    btw, one of the bigger concern is that, are you trying to maintain something like connection pool on you own? if yes then why?

    I take my answer back. Using locks in better answer that using this method.

    0 讨论(0)
提交回复
热议问题