当我调用ConcurrentDictionary.ToArray时,有时我会收到以下错误.错误如下:
System.ArgumentException:索引等于或大于数组的长度,或者字典中的元素数大于从索引到目标数组末尾的可用空间.at System.Collections.Concurrent.ConcurrentDictionary
2.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair2 [] array,Int32 index)at System.Linq.Buffer1..ctor(IEnumerable1 source)at System.Linq.Enumerable.ToArray [TSource](IEnumerable1 source) at ...Cache.SlidingCache2.RemoveExcessAsync(Object state)in ...\SlidingCache.cs:System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)的第141行,位于System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx) System.Threading.ThreadPoolWorkQueue.Dispatch()中的.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
我注意到在多线程场景中,有时在对ConcurrentDictionary进行排序时会出现异常.见堆栈溢出的问题在这里.所以我在排序之前开始使用ConcurrentDictionary.ToArray.在创建阵列时似乎仍然存在问题.
并发字典用于缓存,当达到缓存的设置的最大元素数时,该缓存维护对象并刷新最后访问的对象.多个线程访问缓存,并且在尝试删除旧元素时发生上述错误,因此可以将新元素添加到数组中.请参阅下面的一些代码段:
public class SlidingCache<TKey, TValue> : IDictionary<TKey, TValue>
{
public int MinCount { get; private set; }
public int MaxCount { get; private set; }
private readonly IDictionary<TKey, CacheValue> _cache = new ConcurrentDictionary<TKey, CacheValue>();
public SlidingCache(int minCount=75000, int maxCount=100000)
{
if (minCount <= 2)
throw new ArgumentException("minCount"); …Run Code Online (Sandbox Code Playgroud)