线程安全的List集合(性能比较差..)

由于MS没有提供List的线程安全集合.自己动手写了一个,不过性能…不高..对于性能要求不高的情况下可以使用.

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace System.Collections.Concurrent{线程安全的List集合类型ConcurrentList<T> : IList<T>{创建一个纯种安全的List集合对像(){list = new List<T>();}内部的索引器访问对像List<T> list;锁对像lockInt;(T item){bool gotLock = false;try{splock.Enter(ref gotLock);return list.IndexOf(item);}finally{if (gotLock){splock.Exit();}}}将元素插入 System.Collections.Generic.List元素(int index, T item){bool gotLock = false;try{splock.Enter(ref gotLock);list.Insert(index, item);}finally{if (gotLock){splock.Exit();}}}移除 System.Collections.Generic.List(int index){bool gotLock = false;try{splock.Enter(ref gotLock);list.RemoveAt(index);}finally{if (gotLock){splock.Exit();}}}public T this[int index]{get{System.Threading.Interlocked.Increment(ref lockInt);try{return list[index];}finally{System.Threading.Interlocked.Decrement(ref lockInt);}}set{System.Threading.Interlocked.Increment(ref lockInt);try{list[index] = value;}finally{System.Threading.Interlocked.Decrement(ref lockInt);}}}(T item){bool gotLock = false;try{splock.Enter(ref gotLock);list.Add(item);}finally{if (gotLock){splock.Exit();}}}(){bool gotLock = false;try{splock.Enter(ref gotLock);list.Clear();}finally{if (gotLock){splock.Exit();}}}(T item){bool gotLock = false;try{splock.Enter(ref gotLock);return list.Contains(item);}finally{if (gotLock){splock.Exit();}}}(T[] array, int arrayIndex){bool gotLock = false;try{splock.Enter(ref gotLock);list.CopyTo(array, arrayIndex);}finally{if (gotLock){splock.Exit();}}}public int Count{get{System.Threading.Interlocked.Increment(ref lockInt);try{return list.Count;}finally{System.Threading.Interlocked.Decrement(ref lockInt);}}}public bool IsReadOnly{get { return false; }}从 System.Collections.Generic.List(T item){bool gotLock = false;try{splock.Enter(ref gotLock);return list.Remove(item);}finally{if (gotLock){splock.Exit();}}}public IEnumerator<T> GetEnumerator(){bool gotLock = false;try{splock.Enter(ref gotLock);return list.GetEnumerator();}finally{if (gotLock){splock.Exit();}}}System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator(){return GetEnumerator();}System.Threading.SpinLock splock = new System.Threading.SpinLock();创建源 System.Collections.Generic.List总数public List<T> GetRange(int index, int count){bool gotLock = false;try{splock.Enter(ref gotLock);return list.GetRange(index, count);}finally{if (gotLock){splock.Exit();}}}从 System.Collections.Generic.List要移除的元素数(int index, int count){bool gotLock = false;try{splock.Enter(ref gotLock);list.RemoveRange(index, count);}finally{if (gotLock){splock.Exit();}}}}}

,一个今天胜过两个明天

线程安全的List集合(性能比较差..)

相关文章:

你感兴趣的文章:

标签云: