How to Create a Thread-Safe Generic List?

后端 未结 8 1173
借酒劲吻你
借酒劲吻你 2020-12-08 10:42

I have a Generic List as below

public static readonly List Customers = new List();

I\'m using the below met

8条回答
  •  时光取名叫无心
    2020-12-08 10:58

    If those are the only functions you are using on List then the easiest way is to write a quick wrapper that synchronizes access with a lock

    class MyList { 
      private List _list = new List();
      private object _sync = new object();
      public void Add(T value) {
        lock (_sync) {
          _list.Add(value);
        }
      }
      public bool Find(Predicate predicate) {
        lock (_sync) {
          return _list.Find(predicate);
        }
      }
      public T FirstOrDefault() {
        lock (_sync) {
          return _list.FirstOrDefault();
        }
      }
    }
    

    I highly recommend the approach of a new type + private lock object. It makes it much more obvious to the next guy who inherits your code what the actual intent was.

    Also note that .Net 4.0 introduced a new set of collections specifically aimed at being used from multiple threads. If one of these meets your needs I'd highly recommend using it over rolling your own.

    • ConcurrentStack
    • ConcurrentQueue

提交回复
热议问题