tags:

views:

42

answers:

1

Hi All

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.Id
            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?
+1  A: 

"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.

Jon Skeet
Thanks for the suggestion Jon. I will give this a try.
c0D3l0g1
Changed my volatile Dictionary objects to ConcurrentDictionary and i am no longer receiving the error. I also did what you recommended at the start of my query - it does improve performance, but is negligible. As the dictionary grows, i'm sure the performance gain will become more noticeable. Thanks again!
c0D3l0g1