开发者

.NET LINQ: Check array index and length EXCEPTION

I have the following method:

/// <summary>
/// Gets the specified side of trades.
/// </summary>
/// <param name="tradesDictionary">The trades dictionary.</param>
/// <param name="side">The side.</param>
public IEnumerable<TradeRecord> GetTrades(Dictionary<Guid, TradeRecord> tradesDictionary, Side side)
{
    return (from tradeRecord in tradesDictionary.Values.ToList().AsParallel()
            where (tradeRecord.OrderRecord.PairRecord.Id == _pairId)
               && (tradeRecord.Side == side.ToString())
            orderby tradeRecord.Date, tradeRecord.DateCreated, tradeRecord.I开发者_C百科d
            select tradeRecord);
}

Which causes the following exception:

Destination array is not long enough to copy all the items in the collection. Check array index and length.

The dictionary passed in, is constantly increasing in size. I wasn't getting the error before, the only thing that has changed is the volume of data in the tradesDictionary.

  1. Why does this exception happen?
  2. How do i prevent it from happening?


"The dictionary passed in, is constantly increasing in size"

Do you mean that it's being modified while you're executing this code? That's a no-no. I suspect the ToList call is failing due to this. (After ToList() has executed, the list should be effectively separate from the dictionary.)

Basically Dictionary<TKey, TValue> doesn't support concurrent reading and writing. You might want to look at ConcurrentDictionary<,> which allows you to iterate over it while another thread is writing.

One suggestion to improve performance when it's all working: call side.ToString() once at the start of the method, instead of on every single loop iteration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜